import { z } from 'zod';
import { VIHAR_STATUSES } from '../constants';

// ISO date YYYY-MM-DD
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD');
// HH:MM (24h)
const timeHHMM = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Time must be HH:MM');

export const createViharSchema = z.object({
  viharDate: isoDate,
  plannedStartTime: timeHHMM,
  sadhujiCount: z.number().int().min(0).max(100),
  sadhvijiCount: z.number().int().min(0).max(100),
  otherCount: z.number().int().min(0).max(100),
  headSaintHonorific: z.string().max(50).trim().optional().nullable(),
  headSaintName: z.string().min(2).max(150).trim(),
  samudayId: z.number().int().positive().nullable().optional(),
  departureLocationId: z.number().int().positive(),
  arrivalLocationId: z.number().int().positive(),
  templeDarshan: z.boolean().default(false),
  updhi: z.boolean().default(false),
  remarks: z.string().max(1000).optional().nullable(),
});
export type CreateViharInput = z.infer<typeof createViharSchema>;

export const updateViharSchema = createViharSchema.partial();
export type UpdateViharInput = z.infer<typeof updateViharSchema>;

export const cancelViharSchema = z.object({
  reason: z.string().min(3).max(500).trim(),
});

export const closeViharManualSchema = z.object({
  startTime: timeHHMM,
  endTime: timeHHMM,
  distanceKm: z.number().positive().max(200),
  notes: z.string().max(500).optional(),
});

export const listViharsQuerySchema = z.object({
  date: isoDate.optional(),
  dateFrom: isoDate.optional(),
  dateTo: isoDate.optional(),
  status: z.enum(VIHAR_STATUSES).optional(),
  localityId: z.coerce.number().int().positive().optional(),
  samudayId: z.coerce.number().int().positive().optional(),
  mine: z.coerce.boolean().optional(),
  // Cannot use z.coerce.boolean — Boolean("false") === true. Parse explicitly.
  allocated: z.enum(['true', 'false']).optional().transform((v) => v === undefined ? undefined : v === 'true'),
  page: z.coerce.number().int().min(1).default(1),
  pageSize: z.coerce.number().int().min(1).max(100).default(20),
});
export type ListViharsQuery = z.infer<typeof listViharsQuerySchema>;
