import { z } from 'zod';
import {
  dateTransformSchema,
  defaultTransformSchema,
} from '../shared/shared.dto';

const optionalString = z.preprocess((value) => {
  if (typeof value === 'string' && value.trim() === '') return undefined;
  return value;
}, z.string().trim().optional());

const statusSchema = z.enum(['active', 'inactive', 'deleted']);

export const createLocationSchema = z.object({
  name: z
    .string()
    .trim()
    .min(2, { message: 'Location name must be at least 2 characters long' }),
  location_code: z
    .string()
    .trim()
    .min(1, { message: 'Location code is required' }),
  description: optionalString,
  status: statusSchema.optional(),
});

export const updateLocationSchema = createLocationSchema
  .partial()
  .refine((data) => Object.keys(data).length > 0, {
    message: 'At least one field must be provided',
  });

export const locationResponseSchema = z.object({
  id: z.string().uuid().optional(),
  name: z.string().optional(),
  location_code: z.string().optional(),
  description: defaultTransformSchema,
  status: statusSchema.optional(),
  created_at: dateTransformSchema,
  updated_at: dateTransformSchema,
});

export const locationsResponseSchema = z.array(locationResponseSchema);

export type createLocationDto = z.infer<typeof createLocationSchema>;
export type updateLocationDto = z.infer<typeof updateLocationSchema>;
export type locationResponseDto = z.infer<typeof locationResponseSchema>;
export type locationsResponseDto = z.infer<typeof locationsResponseSchema>;
