import { z } from "zod"
import { PRODUCTION_WORKFLOW_SYSTEM_ROLES, STATION_MAIN_TYPES } from "../enums.js"

const HEX_COLOR_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/

export const StationProductionWorkflowStepSchema = z.object({
    id: z.string().uuid().optional(),
    code: z.string().trim().min(1).max(64).regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i, "Invalid workflow step code"),
    label: z.string().trim().min(1).max(80),
    color: z.string().trim().regex(HEX_COLOR_RE, "Invalid hex color").nullable().default(null),
    position: z.number().int().min(0),
    systemRole: z.enum(PRODUCTION_WORKFLOW_SYSTEM_ROLES),
    active: z.boolean().default(true),
})

export const StationProductionWorkflowSchema = z.object({
    enabled: z.boolean().default(true),
    steps: z.array(StationProductionWorkflowStepSchema).min(2),
}).superRefine((value, ctx) => {
    const activeSteps = value.steps.filter((step) => step.active)
    if (activeSteps.length < 2) {
        ctx.addIssue({ code: z.ZodIssueCode.custom, message: "At least two active workflow steps are required", path: ["steps"] })
        return
    }

    const sorted = [...activeSteps].sort((a, b) => a.position - b.position)
    const codes = new Set<string>()
    sorted.forEach((step, index) => {
        if (codes.has(step.code)) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Duplicate workflow step code: ${step.code}`, path: ["steps", index, "code"] })
        }
        codes.add(step.code)

        if (step.position !== index) {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Workflow step positions must be contiguous starting at 0", path: ["steps", index, "position"] })
        }
    })

    if (sorted[0]?.systemRole !== "START") {
        ctx.addIssue({ code: z.ZodIssueCode.custom, message: "First active step must use START role", path: ["steps", 0, "systemRole"] })
    }
    if (sorted[sorted.length - 1]?.systemRole !== "END") {
        ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Last active step must use END role", path: ["steps", sorted.length - 1, "systemRole"] })
    }

    sorted.slice(1, -1).forEach((step, index) => {
        if (step.systemRole !== "INTERMEDIATE") {
            ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Intermediate steps must use INTERMEDIATE role", path: ["steps", index + 1, "systemRole"] })
        }
    })
})

export const CreateStationSchema = z.object({
    name: z.string().min(2).max(80),
    mainType: z.enum(STATION_MAIN_TYPES)
})

export const UpdateStationSchema = z.object({
    name: z.string().min(2).max(80).optional(),
    mainType: z.enum(STATION_MAIN_TYPES).optional(),
    active: z.boolean().optional(),
}).refine((v) => Object.keys(v).length > 0, {
    message: "At least one field is required"
})

export const UpdateStationProductionWorkflowSchema = StationProductionWorkflowSchema

export const SetStationShopUsersSchema = z.object({
    shopUserIds: z.array(z.string().uuid()).default([])
})

export const SetStationProductsSchema = z.object({
    productIds: z.array(z.string().uuid()).default([])
})

export type CreateStationInput = z.infer<typeof CreateStationSchema>
export type UpdateStationInput = z.infer<typeof UpdateStationSchema>
export type StationProductionWorkflowInput = z.infer<typeof StationProductionWorkflowSchema>
export type UpdateStationProductionWorkflowInput = z.infer<typeof UpdateStationProductionWorkflowSchema>
export type SetStationShopUsersInput = z.infer<typeof SetStationShopUsersSchema>
export type SetStationProductsInput = z.infer<typeof SetStationProductsSchema>
