import { z } from "zod";

const positiveId = z.coerce.number().int().positive();

const slug = z
  .string()
  .trim()
  .min(1)
  .max(140)
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a URL-safe slug");

const mediaInputSchema = z.object({
  url: z.string().trim().min(1).max(512),
  storageKey: z.string().trim().max(1024).nullable().optional(),
  fileName: z.string().trim().max(255).nullable().optional(),
  mimeType: z.string().trim().max(120).nullable().optional(),
  sizeBytes: z.coerce.number().int().min(0).nullable().optional(),
  altText: z.string().trim().max(255).nullable().optional(),
  sortOrder: z.coerce.number().int().min(0).default(0),
  isPrimary: z.boolean().default(false),
});

export const productTypeIdParamSchema = z.object({
  id: positiveId,
});

export const productTypeSlugParamSchema = z.object({
  slug,
});

export const productTypeListQuerySchema = z.object({
  q: z.string().trim().min(1).max(120).optional(),
  page: z.coerce.number().int().min(1).default(1),
  perPage: z.coerce.number().int().min(1).max(100).default(20),
  includeInactive: z.preprocess((value) => {
    if (value === undefined) return undefined;
    if (typeof value === "boolean") return value;
    if (typeof value === "string") {
      if (["true", "1", "yes"].includes(value.toLowerCase())) return true;
      if (["false", "0", "no"].includes(value.toLowerCase())) return false;
    }
    return value;
  }, z.boolean().optional()),
});

export const createProductTypeSchema = z.object({
  name: z.string().trim().min(2).max(120),
  slug: slug.optional(),
  media: z.array(mediaInputSchema).default([]),
});

export const updateProductTypeSchema = createProductTypeSchema
  .partial()
  .extend({
    media: z.array(mediaInputSchema).optional(),
    isActive: z.boolean().optional(),
  })
  .refine(
    (value) => Object.keys(value).length > 0,
    "At least one field is required",
  );
