import assert from "node:assert/strict";
import { describe, test } from "node:test";
import moment from "moment";
import { canExcludeRegistration, canManageVolunteerRoles } from "@/features/opportunities/registrationManagementPolicy";
import { getOpportunityButtonState } from "@/features/shared/opportunityButtonState";
import { canShowReportCertificate } from "@/features/achievements/reportEntryPolicy";
import type { ReportEntry } from "@/features/achievements/services/accountReport";
import { HOME_SECTION_KEYS, resolveHomeSectionOrder } from "@/features/home/homeSectionOrder";
import { submitRequiredInterests } from "@/features/shared/submitRequiredInterests";
import { appendEventOptionalPayload } from "@/features/events/eventOptionalPayload";
import { buildContactFormSchema } from "@/features/info/contactFormSchema";
import { canMarkAttendanceForDate, isDateValidForVolunteer, toApiDate } from "@/features/opportunities/components/volunteerListHelpers";
import { reviewedChoices } from "@/features/shared/reviewChoices";

const source = { start_date: "2026-11-05", start_time: "10:00", end_date: "2026-11-06", end_time: "12:00" };
const at = (time: string) => moment.parseZone(time);

describe("final client review: exclusion and exact deadlines", () => {
  test("late joining and attendance dates use Kuwait day even across UTC midnight", () => {
    const row = { registration_date: "2026-11-01T22:30:00Z" };
    assert.equal(toApiDate(row.registration_date), "2026-11-02");
    assert.equal(isDateValidForVolunteer(row, "2026-11-01", "2026-11-01"), false);
    assert.equal(canMarkAttendanceForDate(row, "2026-11-02", "02:00:00"), true);
    assert.equal(canMarkAttendanceForDate(row, "2026-11-02", "01:00:00"), false);
    assert.equal(toApiDate("2026-11-02"), "2026-11-02");
  });
  test("registration closes at its exact Kuwait instant including offset-free timestamps", () => {
    const item = { ...source, registration_closes_at: "2026-11-04 10:00:00" };
    assert.equal(getOpportunityButtonState(item, at("2026-11-04T09:59:59+03:00")), "register");
    assert.equal(getOpportunityButtonState(item, at("2026-11-04T10:00:00+03:00")), "closed");
    assert.equal(canExcludeRegistration(item, at("2026-11-04T07:00:00Z")), false);
  });
  test("an explicit row permission never extends exclusion past the first scattered session", () => {
    const item = { ...source, can_exclude: true, exclusion_closes_at: "2026-11-08T12:00:00+03:00", time_slots: [{ date: "2026-11-03", start_time: "09:00", end_time: "11:00" }] };
    assert.equal(canExcludeRegistration(item, at("2026-11-03T08:59:59+03:00")), true);
    assert.equal(canExcludeRegistration(item, at("2026-11-03T09:00:00+03:00")), false);
  });
  test("no-deadline exclusion stops at actual start and cannot restart on reopening", () => {
    assert.equal(canExcludeRegistration(source, at("2026-11-05T09:59:59+03:00")), true);
    assert.equal(canExcludeRegistration(source, at("2026-11-05T10:00:00+03:00")), false);
  });
  test("paid, cancelled, missing schedule and explicit refusal do not allow exclusion", () => {
    const now = at("2026-11-01T10:00:00+03:00");
    for (const item of [{ ...source, is_paid: true }, { ...source, can_exclude: false }, { ...source, opportunity_status: "cancelled" }, {}]) assert.equal(canExcludeRegistration(item, now), false);
  });
  test("role transfer closes at the final overnight end or cancellation", () => {
    const item = { ...source, time_slots: [{ date: "2026-11-06", start_time: "23:00", end_time: "01:00" }] };
    assert.equal(canManageVolunteerRoles(item, at("2026-11-07T00:59:59+03:00")), true);
    assert.equal(canManageVolunteerRoles(item, at("2026-11-07T01:00:00+03:00")), false);
    assert.equal(canManageVolunteerRoles({ ...item, opportunity_status: "cancelled" }, at("2026-11-01T10:00:00+03:00")), false);
  });
});

const reportRow = (extra: Partial<ReportEntry>): ReportEntry => ({ id: 1, title: "Example", type: "Course", date: "2026-11-05", beneficiaries: null, attendees: 1, scheduled_hours: null, actual_hours: null, economic_impact: null, certificate_url: "https://example.org/certificate.pdf", ...extra });
describe("final client review: report certificate scope", () => {
  test("course/internship participants have certificates, providers have fees instead", () => {
    for (const type of ["Course", "Internship", "دورة", "تدريب عملي"]) {
      assert.equal(canShowReportCertificate(reportRow({ type, role: "participant" }), "individual"), true);
      assert.equal(canShowReportCertificate(reportRow({ type, role: "provider" }), "individual"), false);
    }
  });
  test("a supplied URL cannot turn a space or workshop into a certificate type", () => {
    for (const type of ["Class/Workshop", "Consultation", "مساحة", "درس أو ورشة"]) for (const kind of ["individual", "team", "organization"] as const) assert.equal(canShowReportCertificate(reportRow({ type }), kind), false);
  });
  test("the stable learning type takes precedence over localized display text", () => {
    assert.equal(canShowReportCertificate(reportRow({ type: "دورة متخصصة", learning_type: "course" }), "organization"), true);
    assert.equal(canShowReportCertificate(reportRow({ type: "Course", learning_type: "space" }), "organization"), false);
  });
});

describe("final client review: homepage order and required interests", () => {
  test("the actual volunteering choice endpoint retires old tags and preserves renamed IDs", () => {
    const choices = [{ id: 1, value_ar: "عام", value_en: "General" }, { id: 2, value_ar: "متقاعدين", value_en: "Retirees" }, { id: 3, value_ar: "شباب", value_en: "Youth", is_active: false }];
    assert.deepEqual(reviewedChoices("volunteer_opportunity_interest", choices), [{ id: 2, value_ar: "كبار السن", value_en: "Older people" }]);
    assert.equal(reviewedChoices("type_of_support", [{ id: 9, value_ar: "آخر", value_en: "Other" }])[0].value_ar, "أخرى");
  });
  test("discovery order is fixed, remaining CMS order is respected and all sections survive", () => {
    const result = resolveHomeSectionOrder(["events", "sponsors", "events", "unknown"]);
    assert.deepEqual(result.slice(0, 6), ["hero", "statistics", "volunteer", "development", "community", "events"]);
    assert.equal(result[6], "sponsors");
    assert.deepEqual([...result].sort(), [...HOME_SECTION_KEYS].sort());
    assert.deepEqual(resolveHomeSectionOrder(), HOME_SECTION_KEYS);
  });
  test("an interest validation error cannot trigger an untagged retry", async () => {
    const data = new FormData(); data.append("interest_ids[]", "42");
    const rejection = { response: { data: { response_status: { validation_errors: { "interest_ids.0": ["Invalid ID"] } } } } };
    let calls = 0;
    await assert.rejects(submitRequiredInterests(data, async payload => { calls++; assert.equal(payload.get("interest_ids[]"), "42"); throw rejection; }), error => error === rejection);
    assert.equal(calls, 1);
  });
  test("valid multiple interests are preserved verbatim", async () => {
    const data = new FormData(); data.append("interest_ids[]", "42"); data.append("interest_ids[]", "87");
    const outcome = await submitRequiredInterests(data, async payload => payload.getAll("interest_ids[]"));
    assert.deepEqual(outcome, { result: ["42", "87"], interestsDropped: false });
  });
});

describe("final client review: event optional values and contact intake", () => {
  test("no-registration clears an old link, optional gender and all removed sponsors", () => {
    const data = new FormData(); appendEventOptionalPayload(data, { participation_type_value_en: "Free Event", registration_link: "https://example.org/old", gender: "", sponsors: [] });
    assert.equal(data.get("registration_link"), ""); assert.equal(data.get("gender_id"), ""); assert.equal(data.get("sponsor_organization_ids"), "none");
  });
  test("registration mode preserves its link and deduplicates sponsor organization IDs in order", () => {
    const data = new FormData(); appendEventOptionalPayload(data, { participation_type_value_en: "Paid Event", registration_link: " https://example.org/register ", gender: "3", sponsors: [{ sponsorId: "12" }, { sponsorId: "12" }, { sponsorId: "" }, { sponsorId: "24" }] });
    assert.equal(data.get("registration_link"), "https://example.org/register"); assert.equal(data.get("gender_id"), "3"); assert.deepEqual(data.getAll("sponsor_organization_ids[]"), ["12", "24"]);
  });
  test("contact name is optional while email and message remain mandatory", async () => {
    const schema = buildContactFormSchema();
    assert.equal(await schema.isValid({ name: "", email: "person@example.org", message: "Hello" }), true);
    assert.equal(await schema.isValid({ name: "", email: "", message: "Hello" }), false);
    assert.equal(await schema.isValid({ email: "person@example.org", message: "" }), false);
  });
});
