import { z } from "zod";

const timeString = z
  .string()
  .regex(/^([01]\d|2[0-3]):[0-5]\d$/, "Use HH:MM (24h)");

export const checkInSchema = z.object({
  body: z.object({
    note: z.string().max(500).optional(),
    imageUrl: z.string().max(1000).optional(),
    location: z
      .object({
        latitude: z.number().optional(),
        longitude: z.number().optional(),
        address: z.string().optional(),
      })
      .optional(),
  }),
});

export const checkOutSchema = z.object({
  body: z.object({
    note: z.string().max(500).optional(),
    workSummary: z.string().max(2000).optional(),
    imageUrl: z.string().max(1000).optional(),
    location: z
      .object({
        latitude: z.number().optional(),
        longitude: z.number().optional(),
        address: z.string().optional(),
      })
      .optional(),
  }),
});

export const listMyAttendanceSchema = z.object({
  query: z.object({
    from: z.string().optional(),
    to: z.string().optional(),
  }),
});

export const listAllAttendanceSchema = z.object({
  query: z.object({
    from: z.string().optional(),
    to: z.string().optional(),
    userId: z.string().optional(),
    status: z.enum(["pending", "approved", "rejected"]).optional(),
  }),
});

// Backward-compatible: used by GET /attendance to serve both admins and regular users.
// For non-admin users, userId/status are ignored.
export const listAttendanceSchema = listAllAttendanceSchema;

export const approveAttendanceSchema = z.object({
  params: z.object({
    id: z.string(),
  }),
  body: z.object({
    status: z.enum(["approved", "rejected"]),
    approvalNote: z.string().max(500).optional(),
  }),
});

export const updateAttendancePolicySchema = z.object({
  body: z
    .object({
      weekdayStart: timeString.optional(),
      weekdayEnd: timeString.optional(),
      fridayStart: timeString.optional(),
      fridayEnd: timeString.optional(),
      saturdayOff: z.boolean().optional(),
      freeAbsencesPerMonth: z.number().int().min(0).max(31).optional(),
    })
    .refine(
      (v) => Object.keys(v || {}).length > 0,
      "At least one field is required"
    ),
});

export const monthlyReportSchema = z.object({
  query: z.object({
    month: z
      .string()
      .regex(/^\d{1,2}$/)
      .transform((s) => Number(s))
      .refine((n) => n >= 1 && n <= 12, "Invalid month"),
    year: z
      .string()
      .regex(/^\d{4}$/)
      .transform((s) => Number(s))
      .refine((n) => n >= 2000 && n <= 2100, "Invalid year"),
    userId: z.string().optional(),
    scope: z.enum(["me", "all"]).optional(),
  }),
});
