import { z } from 'zod';
import { imageSchema } from '../shared/shared.dto';

export const DepartmentSchema = z.object({
  id: z.string(),
  name: z.string(),
});

export const optionalDate = z.preprocess(
  (value) => {
    if (value === undefined || value === null || value === '') {
      return value;
    }
    if (value instanceof Date) {
      return value;
    }
    if (typeof value === 'string') {
      return new Date(value);
    }
    return value;
  },
  z
    .date()
    .transform((date) => date.toISOString())
    .optional()
    .nullable(),
);

export const monthHistoryQuerySchema = z.object({
  month: z.preprocess((value) => {
    if (value === undefined || value === null || value === '') {
      return new Date().getMonth() + 1;
    }
    const parsed = Number(value);
    return Number.isNaN(parsed) ? value : parsed;
  }, z.number().int().min(1).max(12)),
  year: z.preprocess((value) => {
    if (value === undefined || value === null || value === '') {
      return new Date().getFullYear();
    }
    const parsed = Number(value);
    return Number.isNaN(parsed) ? value : parsed;
  }, z.number().int().min(1970).max(3000)),
  data_scope: z.enum(['own', 'all']).optional(),
});

export const monthHistoryResponseSchema = z.object({
  id: z.string(),
  title: z.string(),
  content: z.string().optional().nullable(),
  date: optionalDate,
  start_date: optionalDate,
  end_date: optionalDate,
  departments: z.array(DepartmentSchema).nullable(),
  department: DepartmentSchema.nullable(),
  status: z.string().optional().nullable(),
  image: imageSchema.nullable(),
  name: z.string().optional().nullable(),
  type: z.string().optional(),
  attendance_type: z.string().optional(),
  priority: z.string().optional().nullable(),
  check_in: optionalDate,
  check_out: optionalDate,
  break_hours: z.number().nullable(),
  total_working_hours: z.number().nullable(),
  lunch_start: optionalDate,
  lunch_end: optionalDate,
  breaks: z.array(
    z.object({
      break_start: optionalDate,
      break_end: optionalDate,
      note: z.string().optional().nullable(),
    }),
  ),
  note: z.string().optional(),
});

export const monthHistoryResponseArraySchema = z.array(
  monthHistoryResponseSchema,
);

export type monthHistoryQueryDto = z.infer<typeof monthHistoryQuerySchema>;
export type monthHistoryResponseDto = z.infer<
  typeof monthHistoryResponseSchema
>;
export type monthHistoryResponseArrayDto = z.infer<
  typeof monthHistoryResponseArraySchema
>;
