import { GradeRulesDraft } from "@/lib/rule-set";

type ValidateOptions = {
  canAllowBoys?: boolean;
  canAllowGirls?: boolean;
};

export function validateGradeRulesStep(
  stepId: number,
  draft: GradeRulesDraft | null,
  options: ValidateOptions = {},
): Record<string, string> {
  const errors: Record<string, string> = {};
  if (!draft) {
    return { form: "پیش‌نویس بارگذاری نشده است." };
  }

  const canAllowBoys = options.canAllowBoys ?? true;
  const canAllowGirls = options.canAllowGirls ?? true;

  if (stepId === 2) {
    const boys = canAllowBoys && draft.allowBoys;
    const girls = canAllowGirls && draft.allowGirls;
    if (!boys && !girls) {
      errors.gender = "حداقل یک جنسیت مجاز (پسر یا دختر) باید انتخاب شود.";
    }
    const minAge = draft.min_age.trim() ? Number(draft.min_age) : null;
    const maxAge = draft.max_age.trim() ? Number(draft.max_age) : null;
    if (minAge != null && maxAge != null && minAge > maxAge) {
      errors.min_age = "حداقل سن نباید بزرگ‌تر از حداکثر سن باشد.";
    }
  }

  if (stepId === 8 && draft.followupMode === "exam") {
    if (!draft.examTitle.trim() && !draft.examAddress.trim()) {
      errors.examTitle = "محل برگزاری آزمون را مشخص کنید.";
    }
    if (!draft.examStartsAt) {
      errors.examStartsAt = "تاریخ شروع آزمون را مشخص کنید.";
    }
  }

  return errors;
}

export function firstGradeRulesError(errors: Record<string, string>): string | null {
  return Object.values(errors)[0] ?? null;
}
