import { z } from "zod";
import { CHECK_TIME_PATTERN, isValidTimezone, type Frequency } from "@/lib/schedule";

// Shared by the settings form and its server action.

// Frequencies offered in the UI. The scheduler already understands the others
// (see FREQUENCY_HOURS); enabling one is a matter of adding it here.
export const ENABLED_FREQUENCIES: Frequency[] = ["EVERY_12_HOURS", "DAILY"];

// Seconds; a response slower than this is recorded as Slow Response.
export const SLOW_THRESHOLD_LIMITS = { min: 1, max: 170 } as const;

export const settingsSchema = z.object({
  frequency: z
    .string()
    .refine((value): value is Frequency => (ENABLED_FREQUENCIES as string[]).includes(value), "Choose a check frequency"),
  checkTime: z.string().trim().regex(CHECK_TIME_PATTERN, "Enter a time as HH:MM (24-hour)"),
  timezone: z.string().trim().min(1, "Timezone is required").refine(isValidTimezone, "Unknown timezone"),
  slowThresholdSeconds: z
    .string()
    .trim()
    .regex(/^\d+$/, "Slow-response threshold must be a whole number of seconds")
    .transform(Number)
    .pipe(
      z
        .number()
        .min(SLOW_THRESHOLD_LIMITS.min, `Slow-response threshold must be between ${SLOW_THRESHOLD_LIMITS.min} and ${SLOW_THRESHOLD_LIMITS.max} seconds`)
        .max(SLOW_THRESHOLD_LIMITS.max, `Slow-response threshold must be between ${SLOW_THRESHOLD_LIMITS.min} and ${SLOW_THRESHOLD_LIMITS.max} seconds`),
    ),
});

export type SettingsInput = { frequency: Frequency; checkTime: string; timezone: string; slowThresholdSeconds: number };
export type SettingsField = keyof SettingsInput;
export type SettingsFieldErrors = Partial<Record<SettingsField, string>>;

export function settingsFormValues(formData: FormData) {
  const text = (name: string) => String(formData.get(name) ?? "");
  return {
    frequency: text("frequency"),
    checkTime: text("checkTime"),
    timezone: text("timezone"),
    slowThresholdSeconds: text("slowThresholdSeconds"),
  };
}

export type SettingsFormValues = ReturnType<typeof settingsFormValues>;

export function validateSettings(
  values: SettingsFormValues,
): { ok: true; data: SettingsInput } | { ok: false; fieldErrors: SettingsFieldErrors } {
  const parsed = settingsSchema.safeParse(values);
  if (parsed.success) return { ok: true, data: parsed.data as SettingsInput };

  const fieldErrors: SettingsFieldErrors = {};
  for (const issue of parsed.error.issues) {
    const field = issue.path[0] as SettingsField | undefined;
    if (field && !fieldErrors[field]) fieldErrors[field] = issue.message;
  }
  return { ok: false, fieldErrors };
}
