import { z } from "zod";

const passwordSchema = z.string().min(6).max(120);

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

  return value;
};

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

export const userCreateSchema = z.object({
  name: z.string().min(2).max(180),
  email: z.string().email(),
  password: passwordSchema,
  role: z.enum(["admin", "operator", "viewer"]),
  isActive: z.boolean().default(true)
});

export const userPatchSchema = z
  .object({
    name: z.string().min(2).max(180).optional(),
    email: z.string().email().optional(),
    password: z.preprocess(emptyToUndefined, passwordSchema.optional()),
    role: z.enum(["admin", "operator", "viewer"]).optional(),
    isActive: z.boolean().optional()
  })
  .refine((value) => Object.keys(value).length > 0, {
    message: "At least one field must be provided"
  });
