import { z } from "zod";

const emptyToNull = (value: unknown) => {
  if (typeof value === "string" && value.trim() === "") {
    return null;
  }

  return value;
};

const priceSchema = z.preprocess((value) => {
  if (value === null || value === undefined) {
    return null;
  }

  if (typeof value === "string") {
    const normalized = value.trim().replace(",", ".");

    if (normalized === "") {
      return null;
    }

    return Number(normalized);
  }

  return value;
}, z.number().finite().min(0).max(100_000_000).nullable());

export const itemParamsSchema = z.object({
  id: z.string().uuid()
});

export const itemQuerySchema = z.object({
  categoryId: z.string().uuid().optional(),
  status: z.enum(["all", "active", "service", "retired"]).optional(),
  search: z.string().optional(),
  includeInactive: z
    .union([z.boolean(), z.string()])
    .optional()
    .transform((value) => value === true || value === "true")
});

export const itemBodySchema = z.object({
  categoryId: z.string().uuid(),
  name: z.string().min(2).max(160),
  serialNumber: z.preprocess(emptyToNull, z.string().max(160).nullable().optional()),
  assetTag: z.preprocess(emptyToNull, z.string().max(160).nullable().optional()),
  suggestedDayRate: priceSchema,
  status: z.enum(["active", "service", "retired"]),
  notes: z.preprocess(emptyToNull, z.string().max(2000).nullable().optional()),
  isVisibleOnTimeline: z.boolean().default(true)
});

export const itemPatchSchema = itemBodySchema.partial().refine((value) => Object.keys(value).length > 0, {
  message: "At least one field must be provided"
});
