import { z } from 'zod'

const dateField = z.string().optional().nullable().transform(v => (v && v.trim() !== '' ? new Date(v) : null))

export function validateDateOrder(
  data: { start_date: Date | null; end_date: Date | null },
  ctx: z.RefinementCtx,
) {
  if (data.start_date && data.end_date && data.end_date < data.start_date) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['end_date'], message: 'Einddatum moet na startdatum liggen' })
  }
}

export const createSprintSchema = z
  .object({
    productId: z.string(),
    sprint_goal: z.string().min(1, 'Sprint Goal is verplicht').max(500),
    start_date: dateField,
    end_date: dateField,
    pbi_id: z
      .string()
      .nullable()
      .optional()
      .transform(v => (v && v.trim() !== '' ? v : null)),
  })
  .superRefine(validateDateOrder)

export const updateSprintDatesSchema = z
  .object({
    id: z.string(),
    start_date: dateField,
    end_date: dateField,
  })
  .superRefine(validateDateOrder)

export const updateSprintGoalSchema = z.object({
  id: z.string(),
  sprint_goal: z.string().min(1, 'Sprint Goal is verplicht').max(500),
})

export type CreateSprintInput = z.infer<typeof createSprintSchema>
export type UpdateSprintDatesInput = z.infer<typeof updateSprintDatesSchema>
export type UpdateSprintGoalInput = z.infer<typeof updateSprintGoalSchema>
