// delegationFormSchema.ts
import * as z from "zod";
import { t } from "i18next";

const MIN_END_DATE_LEAD_TIME_MS = 2 * 60 * 1000;
const MIN_START_DATE_LEAD_TIME_MS = 0;

const validateStartDate = (startDate: Date, ctx: z.RefinementCtx) => {
  const minimumAllowedDate = new Date(Date.now() + MIN_START_DATE_LEAD_TIME_MS);

  if (startDate.getTime() < minimumAllowedDate.getTime()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["startDate"],
      message: t(
        "delegation.startDateMinimumNowError",
        "Start date must be now or in the future",
      ),
    });
  }
};

const validateEndDate = (endDate: Date, ctx: z.RefinementCtx) => {
  const minimumAllowedDate = new Date(Date.now() + MIN_END_DATE_LEAD_TIME_MS);

  if (endDate.getTime() < minimumAllowedDate.getTime()) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["endDate"],
      message: t(
        "delegation.endDateMinimumFutureError",
        "End date must be at least 2 minutes from now",
      ),
    });
  }
};

const validateEndAfterStart = (
  startDate: Date | undefined,
  endDate: Date,
  ctx: z.RefinementCtx,
) => {
  if (
    startDate instanceof Date &&
    !Number.isNaN(startDate.getTime()) &&
    endDate instanceof Date &&
    !Number.isNaN(endDate.getTime()) &&
    endDate.getTime() <= startDate.getTime()
  ) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["endDate"],
      message: t(
        "delegation.endDateBeforeStartError",
        "End date must be after start date",
      ),
    });
  }
};

export const delegationFormSchema = z
  .object({
    positionId: z.string().min(1, "Position is required"),
    employeeId: z.string().min(1, "Delegated employee is required"),
    startDate: z.date(),
    endDate: z.date(),
    internalCC: z.array(z.string()).optional(),
    signatureId: z.string().optional(),
    stampId: z.string().optional(),
    language: z.enum(["en", "am"]).optional(),
    locale: z.enum(["en", "am"]).optional(),
    // delegationLetterId: z.string().optional(),
    //recordType: z.enum(["outgoing", "incoming"]).optional(),
  })
  .superRefine((values, ctx) => {
    validateStartDate(values.startDate, ctx);
    validateEndDate(values.endDate, ctx);
    validateEndAfterStart(values.startDate, values.endDate, ctx);
  });

export const editdelegationFormSchema = z
  .object({
    positionId: z.string().min(1, "Position is required"),
    employeeId: z.string().min(1, "Delegated employee is required"),
    endDate: z.date(),
    startDate: z.date(),
    internalCC: z.array(z.string()).optional(),
    stampId: z.string().optional(),
    signatureId: z.string().optional(),
    language: z.enum(["en", "am"]).optional(),
  })
  .superRefine((values, ctx) => {
    validateStartDate(values.startDate, ctx);
    validateEndDate(values.endDate, ctx);
    validateEndAfterStart(values.startDate, values.endDate, ctx);
  });
