import { z } from "zod"
import { EmployeeType, WageType } from "@garage/api"

const relationFieldSchema = z
    .object({ value: z.string(), label: z.string() })
    .nullable()

const optionalNumericField = z.preprocess(
    (value) => {
        if (value === "" || value === null || value === undefined) {
            return null
        }
        return Number(value)
    },
    z.number().finite().nullable(),
)

const optionalIntegerIdField = z.preprocess(
    (value) => {
        if (value === "" || value === null || value === undefined) {
            return null
        }
        return Number(value)
    },
    z.number().int().positive().nullable(),
)

const STATUS_OPTIONS = ["active", "inactive"] as const
const TYPE_OPTIONS = EmployeeType
const WAGE_TYPE_OPTIONS = WageType

const employeeFormSchema = z.object({
    department: relationFieldSchema,
    country: relationFieldSchema,
    shop_calender: relationFieldSchema,
    shop_timing: relationFieldSchema,
    role_id: optionalIntegerIdField,
    first_name: z.string().trim().min(1, "First name is required").max(50, "First name must be at most 50 characters"),
    last_name: z.string().trim().min(1, "Last name is required").max(50, "Last name must be at most 50 characters"),
    email: z.string().trim().min(1, "Email is required").email("Enter a valid email address").max(100, "Email must be at most 100 characters"),
    password: z.string().min(6, "Password must be at least 6 characters"),
    phone: z.string().trim().max(30, "Phone must be at most 30 characters").optional().or(z.literal("")),
    designation: z.string().trim().max(50, "Designation must be at most 50 characters").optional().or(z.literal("")),
    salary: optionalNumericField,
    wage_type: z.enum(WAGE_TYPE_OPTIONS).nullable(),
    status: z.enum(STATUS_OPTIONS),
    type: z.enum(TYPE_OPTIONS),
    track_attendance: z.boolean(),
    notify_owner_when_punch_in_out: z.boolean(),
    geo_fence_radius: optionalNumericField,
})

type EmployeeFormValues = z.infer<typeof employeeFormSchema>

export { employeeFormSchema, relationFieldSchema, STATUS_OPTIONS, TYPE_OPTIONS, WAGE_TYPE_OPTIONS }
export type { EmployeeFormValues }
