import { z } from "zod"
import { LOGISTICS_STEP_TYPES, TRANSFER_HANDLER_MODES } from "../enums.js"

/* ─── Step input schema ──────────────────────────────────────────────── */

export const createLogisticsRouteStepSchema = z.object({
    /** Station de production (PRODUCTION uniquement) */
    stationId: z.string().uuid().nullish(),
    /** Station de destination (TRANSPORT uniquement) */
    destinationStationId: z.string().uuid().nullish(),
    stepType: z.enum(LOGISTICS_STEP_TYPES),
    position: z.number().int().min(0),
    label: z.string().max(120).nullish(),
    handlerMode: z.enum(TRANSFER_HANDLER_MODES).nullish(),
    assignedRunnerId: z.string().uuid().nullish(),
    estimatedMinutes: z.number().int().min(0).nullish(),
}).refine(
    (step) => step.stepType !== "PRODUCTION" || (step.stationId != null),
    { message: "PRODUCTION requiert une station (stationId)", path: ["stationId"] }
).refine(
    (step) => step.stepType !== "TRANSPORT" || (step.destinationStationId != null),
    { message: "TRANSPORT requiert une station de destination (destinationStationId)", path: ["destinationStationId"] }
)

/* ─── Route schemas ──────────────────────────────────────────────────── */

export const createLogisticsRouteSchema = z.object({
    name: z.string().min(2).max(120),
    description: z.string().max(500).nullish(),
    isDefault: z.boolean().optional(),
    steps: z.array(createLogisticsRouteStepSchema).min(1, "Au moins 1 étape"),
}).refine(
    (data) => data.steps[0]?.stepType === "PRODUCTION",
    { message: "La première étape doit être de type PRODUCTION", path: ["steps"] }
).refine(
    (data) => {
        // Pas deux étapes consécutives du même type
        for (let i = 1; i < data.steps.length; i++) {
            if (data.steps[i]?.stepType === data.steps[i - 1]?.stepType) return false
        }
        return true
    },
    { message: "Deux étapes consécutives ne peuvent pas être du même type (alterner PRODUCTION / TRANSPORT)", path: ["steps"] }
)

export const updateLogisticsRouteSchema = z.object({
    name: z.string().min(2).max(120).optional(),
    description: z.string().max(500).nullish(),
    isDefault: z.boolean().optional(),
    active: z.boolean().optional(),
    steps: z.array(createLogisticsRouteStepSchema).min(1).optional(),
}).refine(
    (data) => {
        if (!data.steps) return true
        return data.steps[0]?.stepType === "PRODUCTION"
    },
    { message: "La première étape doit être de type PRODUCTION", path: ["steps"] }
).refine(
    (data) => {
        if (!data.steps) return true
        for (let i = 1; i < data.steps.length; i++) {
            if (data.steps[i]?.stepType === data.steps[i - 1]?.stepType) return false
        }
        return true
    },
    { message: "Deux étapes consécutives ne peuvent pas être du même type", path: ["steps"] }
)
