import assert from "node:assert/strict";
import { describe, test } from "node:test";
import moment from "moment";
import { getOpportunityButtonState } from "@/features/shared/opportunityButtonState";
import { deriveVolunteerEventView } from "@/features/opportunities/components/volunteer-event/volunteerEventView";
import type { VolunteerOpportunityDetail } from "@/features/opportunities/components/volunteer-event/types";
import { buildOrganizerAccountValidation } from "@/features/profile/components/organizerAccountValidation";
import { licenseNumberRequiredFor, licenseUploadRequiredFor } from "@/features/shared/formRules";
import { getPublishPermissions, getPublisherKind } from "@/lib/publishPermissions";
import { formatAmount } from "@/features/opportunities/payment";
import { isRoleCapacityWithinTotal, unassignedRoleOption } from "@/features/opportunities/roleCapacity";
import { mapFormApiErrors } from "@/features/shared/formApiErrors";
import { submitRequiredInterests } from "@/features/shared/submitRequiredInterests";

const now = moment.parseZone("2026-11-01T12:00:00+03:00");
const running = { opportunity_type: "volunteer_opportunity", start_date: "2026-10-31", end_date: "2026-11-03", is_registration_open: true, is_paid: false };
describe("PDF pages 13/16: explicit running volunteering reopening", () => {
  test("an initially open flag alone does not reopen a started opportunity", () => {
    assert.equal(getOpportunityButtonState(running, now), "started");
    assert.equal(getOpportunityButtonState({ ...running, can_register_while_running: true }, now), "register");
  });
  test("reopened registration remains subject to capacity, closing time and actual end", () => {
    const reopened = { ...running, can_register_while_running: true };
    assert.equal(getOpportunityButtonState({ ...reopened, participants_needed: 1, registered_volunteers_count: 1 }, now), "full");
    assert.equal(getOpportunityButtonState({ ...reopened, registration_closes_at: "2026-11-01T12:00:00+03:00" }, now), "closed");
    assert.equal(getOpportunityButtonState({ ...reopened, end_date: "2026-11-01", end_time: "12:00" }, now), "ended");
    assert.equal(getOpportunityButtonState({ ...reopened, opportunity_type: "learn_serve_opportunity" }, now), "started");
  });
  test("the organizer can explicitly reopen a started opportunity that was initially open", () => {
    const detail = { ...running, id: 2, title_ar: "فرصة", title_en: "Opportunity", start_time: "10:00", end_time: "14:00", created_by: { id: 8 }, opportunity_images: [], total_roles: 0 } as VolunteerOpportunityDetail;
    const view = deriveVolunteerEventView(detail, { id: 8, signedIn: true, hasAuthToken: true, isVerified: true, userType: "organization" }, now);
    assert.equal(view.canReopenRegistration, true);
    assert.equal(view.canCloseRegistration, false);
  });
});

const choices = [
  { value: "1", label: "Team", rawValue: "Volunteer Team", licenseRequired: false, licenseDocumentRequired: false },
  { value: "2", label: "Commercial", rawValue: "Commercial", licenseRequired: false, licenseDocumentRequired: false },
  { value: "3", label: "Government", rawValue: "Governmental", licenseRequired: true, licenseDocumentRequired: true },
];
describe("PDF pages 9/10: dashboard licensing applies to account editing", () => {
  test("team licensing is required while metadata overrides old organization exemptions", () => {
    for (const rule of [licenseNumberRequiredFor, licenseUploadRequiredFor]) {
      assert.equal(rule(choices, "1"), true);
      assert.equal(rule(choices, "2"), false);
      assert.equal(rule(choices, "3"), true);
    }
  });
  test("account edit rejects clearing a required license but permits the optional case", async () => {
    const schema = buildOrganizerAccountValidation({ t: key => key, orgTypeOptions: choices, keptDocIds: [] });
    for (const organizer_type of ["1", "3"]) await assert.rejects(schema.validateAt("license_number", { organizer_type, license_number: "" }));
    await schema.validateAt("license_number", { organizer_type: "2", license_number: "" });
    await schema.validateAt("license_number", { organizer_type: "1", license_number: "1234" });
  });
});

describe("PDF page 41: publisher types must be known before offering capabilities", () => {
  const user = { user_type: "organization" as const, is_verified: true };
  test("unresolved organization/team type offers no publish capability", () => {
    assert.equal(getPublisherKind(user), null);
    const permissions = getPublishPermissions(user);
    for (const capability of ["volunteer", "development", "developmentPaid", "internship", "events"] as const) assert.equal(permissions[capability], false);
  });
  test("resolved team permits free development only; approved organization gets its matrix", () => {
    const team = getPublishPermissions({ ...user, organizer_type_display: { value_en: "Volunteer Team" } });
    assert.equal(team.development, true); assert.equal(team.developmentPaid, false); assert.equal(team.internship, false); assert.equal(team.events, false);
    const organization = getPublishPermissions({ ...user, organizer_type_display: { value_en: "Commercial" } });
    assert.equal(organization.developmentPaid, true); assert.equal(organization.events, true);
  });
});

test("PDF page 21: money display retains fils rather than rounding them to cents", () => {
  assert.equal(formatAmount("20.105", "KWD"), "20.105 KWD");
  assert.equal(formatAmount("0.200", "KWD"), "0.200 KWD");
  assert.equal(formatAmount("19.905"), "19.905");
});

test("PDF page 39: roles can leave unallocated seats without a delete-all warning", () => {
  assert.equal(isRoleCapacityWithinTotal(10, 0), true);
  assert.equal(isRoleCapacityWithinTotal(10, 7), true);
  assert.equal(isRoleCapacityWithinTotal(10, 10), true);
  assert.equal(isRoleCapacityWithinTotal(10, 11), false);
  assert.equal(isRoleCapacityWithinTotal(10, NaN), false);
});

test("unassigned registration seats require an authoritative positive remaining count", () => {
  assert.equal(unassignedRoleOption(undefined, "ar"), null);
  assert.equal(unassignedRoleOption(0, "ar"), null);
  assert.equal(unassignedRoleOption(-1, "en"), null);
  assert.equal(unassignedRoleOption(1.5, "en"), null);
  assert.equal(unassignedRoleOption(2, "ar")?.remaining_slots, 2);
  assert.equal(unassignedRoleOption(2, "en")?.label, "No assigned role");
});

describe("PDF page 37: validation belongs beside the visible field", () => {
  const error = (fields: Record<string, string[]>) => ({ response: { data: { response_status: { validation_errors: fields } } } });
  test("opportunity API aliases and array failures reach their actual inputs", () => {
    const mapped = mapFormApiErrors(error({ participants_needed: ["Capacity"], "interest_ids.0": ["Interest"], from_age: ["Minimum"], to_age: ["Maximum"], title_en: ["Title"], registration_deadline_hours: ["Deadline"] }), "en", ["participantsNeeded", "_interests", "age", "title_ar", "title_en", "registrationDeadlineHours"]);
    assert.deepEqual(mapped, { participantsNeeded: "Capacity", _interests: "Interest", age: "Minimum · Maximum", title_ar: "Title", registrationDeadlineHours: "Deadline" });
  });
  test("signup keeps its own interest field and maps identity to the visible birthday/nationality", () => {
    assert.deepEqual(mapFormApiErrors(error({ date_of_birth: ["Age"], residency_status: ["Residency"], "interest_ids.2": ["Interest"] }), "en", ["dob", "nationality", "interest_ids"]), { dob: "Age", nationality: "Residency", interest_ids: "Interest" });
  });
  test("form-specific aliases override defaults and unknown API keys do not create hidden fields", () => {
    assert.deepEqual(mapFormApiErrors(error({ location_url: ["Location"], company_name: ["Name"], unknown_key: ["Unknown"] }), "ar", ["locationUrl", "first_name"], { location_url: "locationUrl", company_name: "first_name" }), { locationUrl: "Location", first_name: "Name" });
  });
  test("HTTP 200 failure must not continue into sponsor synchronization or a success screen", async () => {
    const rejection = { key: "fail", response_status: { error: true, validation_errors: { price: ["Invalid"] } } };
    let attempts = 0;
    await assert.rejects(submitRequiredInterests(new FormData(), async () => { attempts++; return rejection; }), value => value === rejection);
    assert.equal(attempts, 1);
  });
});
