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 optionalUuid = z.preprocess((value) => {
  if (typeof value === 'string' && value.trim() === '') return undefined;
  return value;
}, z.string().uuid().optional());

const departmentStatusSchema = z.enum(['active', 'inactive', 'deleted']);
const memberStatusSchema = z.enum([
  'active',
  'deactivated',
  'terminated',
  'deceased',
  'resigned',
  'deleted',
]);
const roleSchema = z.enum(['owner', 'admin', 'member']);

export const departmentMemberSchema = z.object({
  id: z.string().uuid().optional(),
  email: z.string().email().optional(),
  employee_id: z.string().optional(),
  image: z.any().optional(),
  nickname: defaultTransformSchema,
  first_name: z.string().optional(),
  last_name: defaultTransformSchema,
  role: roleSchema.optional(),
  status: memberStatusSchema.optional(),
  phone: defaultTransformSchema,
  work_phone: defaultTransformSchema,
  created_at: dateTransformSchema,
  updated_at: dateTransformSchema,
});

export const createDepartmentSchema = z.object({
  name: z
    .string()
    .trim()
    .min(2, { message: 'Department name must be at least 2 characters long' }),
  department_code: z
    .string()
    .trim()
    .min(1, { message: 'Department code is required' }),
  description: optionalString,
  department_head_id: optionalUuid,
  status: departmentStatusSchema.optional(),
});

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

export const departmentResponseSchema = z.object({
  id: z.string().uuid().optional(),
  name: z.string().optional(),
  department_code: z.string().optional(),
  description: defaultTransformSchema,
  department_head_id: z.string().uuid().optional().nullable(),
  department_head: departmentMemberSchema.optional().nullable(),
  members: z.array(departmentMemberSchema).optional(),
  members_count: z.number().optional(),
  status: departmentStatusSchema.optional(),
  created_at: dateTransformSchema,
  updated_at: dateTransformSchema,
});

export const departmentsResponseSchema = z.array(departmentResponseSchema);

export type createDepartmentDto = z.infer<typeof createDepartmentSchema>;
export type updateDepartmentDto = z.infer<typeof updateDepartmentSchema>;
export type departmentResponseDto = z.infer<typeof departmentResponseSchema>;
export type departmentsResponseDto = z.infer<typeof departmentsResponseSchema>;
