import { z } from 'zod';

const OnceScheduleSchema = z.object({
  type: z.literal('once'),
  at: z.number().int().nonnegative(),
});

const IntervalScheduleSchema = z.object({
  type: z.literal('interval'),
  seconds: z.number().int().positive(),
});

const CronScheduleSchema = z.object({
  type: z.literal('cron'),
  expression: z.string().min(1).max(256),
});

const OnChangeScheduleSchema = z.object({
  type: z.literal('onchange'),
  watch_patterns: z.array(z.string().min(1).max(512)).min(1),
});

export const ScheduleSchema = z.discriminatedUnion('type', [
  OnceScheduleSchema,
  IntervalScheduleSchema,
  CronScheduleSchema,
  OnChangeScheduleSchema,
]);

export const ScheduleIdParamsSchema = z.object({
  id: z.string().min(1).max(256),
});

export const CreateScheduleSchema = z.object({
  name: z.string().min(1).max(256),
  goal: z.string().min(1).max(10_000),
  folder: z.string().min(1).max(2048),
  model: z.string().min(1).max(256).optional(),
  schedule: ScheduleSchema,
});

export const UpdateScheduleSchema = z
  .object({
    name: z.string().min(1).max(256).optional(),
    goal: z.string().min(1).max(10_000).optional(),
    folder: z.string().min(1).max(2048).optional(),
    model: z.string().min(1).max(256).optional(),
    enabled: z.boolean().optional(),
    schedule: ScheduleSchema.optional(),
  })
  .refine(value => Object.keys(value).length > 0, {
    message: 'at least one field must be provided',
  });

export const PauseScheduleSchema = z.object({
  paused: z.boolean().optional(),
});
