import { z } from 'zod';
import { CutCategory } from '@prisma/client';

const geojsonValidator = z.string().refine(
  (val) => {
    try {
      const parsed = JSON.parse(val) as { type: string };
      return parsed.type === 'Polygon' || parsed.type === 'MultiPolygon';
    } catch {
      return false;
    }
  },
  { message: 'Must be valid GeoJSON with type Polygon or MultiPolygon' }
);

export const createCutSchema = z.object({
  name: z.string().min(1, 'Name is required'),
  description: z.string().optional(),
  color: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Must be a hex color').default('#3388ff'),
  opacity: z.number().min(0).max(1).default(0.3),
  category: z.nativeEnum(CutCategory).optional(),
  isPublic: z.boolean().optional().default(false),
  isOfficial: z.boolean().optional().default(false),
  geojson: geojsonValidator,
  bounds: z.string().optional(),
  showLocations: z.boolean().optional().default(true),
  exportEnabled: z.boolean().optional().default(true),
  assignedTo: z.string().optional(),
});

export const updateCutSchema = z.object({
  name: z.string().min(1).optional(),
  description: z.string().nullable().optional(),
  color: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Must be a hex color').optional(),
  opacity: z.number().min(0).max(1).optional(),
  category: z.nativeEnum(CutCategory).nullable().optional(),
  isPublic: z.boolean().optional(),
  isOfficial: z.boolean().optional(),
  geojson: geojsonValidator.optional(),
  bounds: z.string().nullable().optional(),
  showLocations: z.boolean().optional(),
  exportEnabled: z.boolean().optional(),
  assignedTo: z.string().nullable().optional(),
  lastCanvassed: z.string().datetime().nullable().optional(),
  completionPercentage: z.number().int().min(0).max(100).optional(),
});

export const listCutsSchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().positive().max(100).default(20),
  category: z.nativeEnum(CutCategory).optional(),
  search: z.string().optional(),
});

export type CreateCutInput = z.infer<typeof createCutSchema>;
export type UpdateCutInput = z.infer<typeof updateCutSchema>;
export type ListCutsInput = z.infer<typeof listCutsSchema>;
