import { z } from "zod"

const timeRegex = /^([01]\d|2[0-3]):([0-5]\d):([0-5]\d)$/
const optionalTimeFormat = z
    .string()
    .optional()
    .refine((v) => !v || timeRegex.test(v), "Time must be in HH:MM:SS format")

export const DAY_OF_WEEK_VALUES = [
    "saturday",
    "sunday",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
] as const

const shopTimingFormSchema = z
    .object({
        title: z.string().min(1, "Title is required").max(255, "Title cannot exceed 255 characters"),
        day_of_week: z.string().optional(),
        is_closed: z.boolean().default(false),
        // Optional at the field level; required below only when the day is open.
        in_time: optionalTimeFormat,
        out_time: optionalTimeFormat,
        full_day_hours: optionalTimeFormat,
        half_day_hours: optionalTimeFormat,
        punch_in: optionalTimeFormat,
        punch_out: optionalTimeFormat,
        before_time: optionalTimeFormat,
        after_time: optionalTimeFormat,
        is_default: z.boolean().default(false),
    })
    .superRefine((values, ctx) => {
        // When the shop is open, in/out times are mandatory.
        if (!values.is_closed) {
            if (!values.in_time) {
                ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["in_time"], message: "In time is required" })
            }
            if (!values.out_time) {
                ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["out_time"], message: "Out time is required" })
            }
        }
    })

type ShopTimingFormValues = z.infer<typeof shopTimingFormSchema>

export { shopTimingFormSchema }
export type { ShopTimingFormValues }
