/**
 * Full audit (8 Nov 2026) — Auth area regressions.
 *
 * Pure logic is exercised directly; the wiring inside `.tsx` / hook files that
 * this runner cannot mount is pinned by reading the source, stated as such.
 */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, test } from "node:test";

import { appendRegisterPayload } from "@/features/auth/services/authApi";
import { sessionFlagsUpdate } from "@/features/auth/sessionFlags";
import { signupLicenseNumberRequired, signupLicenseUploadRequired } from "@/features/shared/formRules";
import { isValidUrlForPlatform } from "@/features/profile/components/volunteerAccountRules";

const src = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");

describe("F-AUTH-1 team sign-up (PDF p.9)", () => {
  // `/choices/org_type/` never returns «Volunteer Team»: a team's form holds no type at all.
  const orgTypes = [
    { value: "4", label: "Educational", rawValue: "Educational", licenseRequired: false, licenseDocumentRequired: false },
  ];

  test("a team needs the licence number and documents with no organization type", () => {
    assert.equal(signupLicenseNumberRequired(true, orgTypes as never, ""), true);
    assert.equal(signupLicenseUploadRequired(true, orgTypes as never, ""), true);
  });

  test("an organization still follows its type's dashboard switches", () => {
    assert.equal(signupLicenseNumberRequired(false, orgTypes as never, "4"), false);
    assert.equal(signupLicenseUploadRequired(false, orgTypes as never, "4"), false);
  });

  test("neither team form requires the hidden organizer_type", () => {
    for (const file of ["features/auth/components/useEntitiesRegistration.ts", "features/auth/components/useCompleteDetails.ts"]) {
      assert.match(src(file), /organizer_type: isVolunteerTeamJoin \? Yup\.string\(\) :/, file);
    }
  });
});

describe("F-AUTH-2 multipart individual sign-up", () => {
  test("arrays go out as key[] entries, booleans as 1/0, blanks dropped", () => {
    const formData = new FormData();
    appendRegisterPayload(formData, {
      email: "a@b.co",
      interest_ids: ["3", "7"],
      speaks_arabic: true,
      civil_id: undefined,
    });
    assert.deepEqual(formData.getAll("interest_ids[]"), ["3", "7"]);
    assert.equal(formData.get("interest_ids"), null);
    assert.equal(formData.get("speaks_arabic"), "1");
    assert.equal(formData.has("civil_id"), false);
  });
});

describe("F-AUTH-3 session publishing flags follow /account/", () => {
  const user = { is_trainer: false, trainer_types: [], is_publishing_paused: true };

  test("an admin's trainer approval and lifted pause reach the stored session", () => {
    assert.deepEqual(
      sessionFlagsUpdate(user, { is_trainer: true, trainer_types: ["course"], approved_trainer_types: ["course"], is_publishing_paused: false }),
      { is_trainer: true, trainer_types: ["course"], is_publishing_paused: false }
    );
  });

  test("no write when nothing changed or the key is absent", () => {
    assert.equal(sessionFlagsUpdate(user, { is_trainer: false, trainer_types: [], is_publishing_paused: true }), null);
    assert.equal(sessionFlagsUpdate(user, {}), null);
    assert.equal(sessionFlagsUpdate(null, { is_trainer: true }), null);
  });

  test("approved types win over the requested ones", () => {
    assert.deepEqual(
      sessionFlagsUpdate({ is_trainer: true, trainer_types: ["course"] }, { trainer_types: ["course", "workshop"], approved_trainer_types: ["course"] }),
      null
    );
  });

  test("the sync is mounted with the header's account query key", () => {
    const sync = src("components/shared/OrganizerTypeSync.tsx");
    assert.match(sync, /queryKey: \["account-info"\]/);
    assert.match(sync, /sessionFlagsUpdate\(/);
  });
});

describe("F-AUTH-4/5/8 wiring", () => {
  test("social organization onboarding treats awaiting approval as created", () => {
    assert.match(src("features/auth/components/useCompleteDetails.ts"), /organization_status;\s*if \(approval\) \{\s*clearSocialSignupState\(\);/);
  });

  test("the login form points a legacy LinkedIn account at password recovery (A19)", () => {
    assert.match(src("features/auth/components/LoginForm.tsx"), /COMMON\.LEGACY_LINKEDIN_HINT/);
    for (const lang of ["en", "ar"]) {
      const json = JSON.parse(readFileSync(new URL(`../locales/${lang}/translation.json`, import.meta.url), "utf8"));
      assert.ok(json["COMMON.LEGACY_LINKEDIN_HINT"], lang);
    }
  });

  test("the paid-publish bank block reads the IBAN's last four, never the absent full number (BE-187)", () => {
    const fields = src("features/opportunities/components/PayoutBankFields.tsx");
    assert.match(fields, /has_payout_bank_account/);
    assert.match(fields, /bank_account_iban_last4/);
    assert.doesNotMatch(fields, /saved\.number/);
  });
});

describe("F-AUTH-10 pending bank change notice (PDF p.10, A12)", () => {
  test("says the old account stays approved and payouts are on hold, in both locales", () => {
    const en = JSON.parse(readFileSync(new URL("../locales/en/translation.json", import.meta.url), "utf8"));
    const ar = JSON.parse(readFileSync(new URL("../locales/ar/translation.json", import.meta.url), "utf8"));
    assert.match(en["COMMON.BANK_CHANGE_PENDING"], /current approved account stays/);
    assert.match(en["COMMON.BANK_CHANGE_PENDING"], /payouts to you are on hold/);
    assert.match(ar["COMMON.BANK_CHANGE_PENDING"], /يبقى حسابك المعتمد الحالي/);
    assert.match(ar["COMMON.BANK_CHANGE_PENDING"], /يتوقف تحويل مستحقاتك/);
  });
});

describe("F-AUTH-9 volunteer WhatsApp link", () => {
  test("wa.me links are accepted alongside whatsapp.com", () => {
    assert.equal(isValidUrlForPlatform("whatsapp", "https://wa.me/96550000000"), true);
    assert.equal(isValidUrlForPlatform("whatsapp", "https://chat.whatsapp.com/abc"), true);
    assert.equal(isValidUrlForPlatform("whatsapp", "https://example.com/wa.me/1"), false);
  });
});
