/**
 * Full audit (8 Nov 2026) — Auth area, second pass (Auth2) regressions.
 *
 * Pure logic is exercised directly; wiring inside `.tsx` / hook files 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 { keepLetters } from "@/components/ui/digitEntry";
import { digitsOnly, parsePastedOtp } from "@/features/auth/components/otpInput";
import { accountFormField } from "@/features/profile/accountFormErrors";
import { getApiFieldErrors, getApiErrorMessage } from "@/lib/api/errors";
import { mapFormApiErrors } from "@/features/shared/formApiErrors";

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

describe("F-AUTH2-1 guardian name accepts Arabic (PDF p.8, p.37)", () => {
  test("Arabic letters and spaces are kept, digits and symbols dropped", () => {
    assert.equal(keepLetters("محمد أحمد"), "محمد أحمد");
    assert.equal(keepLetters("Sara Ali"), "Sara Ali");
    assert.equal(keepLetters("علي123!@"), "علي");
  });
  test("Input and ModalInput use it for lettersOnly (source pin)", () => {
    for (const file of ["components/ui/Input.tsx", "components/ui/ModalInput.tsx"]) {
      assert.match(src(file), /keepLetters\(e\.target\.value\)/);
      assert.doesNotMatch(src(file), /\[\^A-Za-z\\s\]/);
    }
  });
});

describe("F-AUTH2-2 OTP boxes accept Arabic-Indic digits (p.7)", () => {
  test("typed Arabic digit is converted, not dropped", () => {
    assert.equal(digitsOnly("٧"), "7");
  });
  test("a pasted Arabic code fills all six boxes", () => {
    assert.deepEqual(parsePastedOtp("١٢٣ ٤٥٦"), ["1", "2", "3", "4", "5", "6"]);
  });
});

describe("F-AUTH2-3 speaks Arabic saved for every nationality (p.8)", () => {
  test("the profile save no longer gates the answer on nationality (source pin)", () => {
    const submit = src("features/profile/components/useVolunteerAccountSubmit.ts");
    assert.doesNotMatch(submit, /speaksArabicApplies/);
    assert.match(submit, /speaksArabicToPayload\(values\.speaks_arabic\) !== undefined/);
  });
});

describe("F-AUTH2-4 entity name limit matches the API (max:255)", () => {
  test("sign-up and social onboarding allow 255 characters (source pin)", () => {
    assert.match(src("features/auth/components/useEntitiesRegistration.ts"), /first_name: YupStringMaxLength\(255\)/);
    assert.match(src("features/auth/components/EntitiesRegistrationFields.tsx"), /maxLength=\{255\}/);
    assert.match(src("features/auth/components/useCompleteDetails.ts"), /company_name: YupStringMaxLength\(255\)/);
  });
});

describe("F-AUTH2-5 date-of-birth pickers stop at the minimum age (p.7)", () => {
  test("no birth-date picker allows today any more (source pin)", () => {
    for (const file of [
      "features/auth/components/RegisterVolunteerModalForm.tsx",
      "features/auth/components/VolunteerMandateDetails.tsx",
      "features/profile/components/VolunteerAccountDetailsSection.tsx",
    ]) {
      assert.match(src(file), /maxDate=\{maxDateOfBirthFor\(MIN_SIGNUP_AGE\)\}/);
    }
  });
});

describe("F-AUTH2-6 profile picture: JPEG/WebP accepted, server reason shown", () => {
  test("avatar and logo pickers accept the API's image types (source pin)", () => {
    for (const file of [
      "features/profile/components/VolunteerAvatarField.tsx",
      "features/profile/components/OrganizerAccountSection.tsx",
    ]) {
      assert.match(src(file), /accept="image\/png,image\/jpeg,image\/webp"/);
    }
  });
  test("upload failure reports the API message (source pin)", () => {
    for (const file of [
      "features/profile/components/useProfilePictureUpload.ts",
      "features/profile/components/useOrganizerLogoUpload.ts",
    ]) {
      assert.match(src(file), /getApiErrorMessage\(\s*error,/);
    }
  });
});

describe("F-AUTH2-7 account edit: array-item errors land on the field (p.37)", () => {
  test("Laravel item keys map to the form field", () => {
    assert.equal(accountFormField("new_documents.0"), "documents");
    assert.equal(accountFormField("interest_ids.2"), "_interests");
    assert.equal(accountFormField("experience"), "experience_field");
    assert.equal(accountFormField("civil_id"), "civil_id");
  });
});

describe("error helpers: both envelopes, locale of the legacy pair", () => {
  test("current envelope (response_status.validation_errors)", () => {
    const error = { response: { data: { key: "fail", msg: "Validation error", response_status: { error: true, validation_errors: { civil_id: ["taken"] } } } } };
    assert.deepEqual(getApiFieldErrors(error, "ar"), { civil_id: "taken" });
  });
  test("legacy { en, ar } pair picks the reader's language", () => {
    const error = { response: { data: { errors: { username: { en: "fixed", ar: "ثابت" } } } } };
    assert.equal(getApiErrorMessage(error, "ar"), "ثابت");
    assert.equal(getApiErrorMessage(error, "en"), "fixed");
  });
  test("legacy pair under validation_errors (Username::changeRefusal) maps to the form field", () => {
    const error = { response_status: { validation_errors: { username: { en: "fixed", ar: "ثابت" } } } };
    assert.deepEqual(mapFormApiErrors(error, "ar", ["nickname"], { username: "nickname" }), { nickname: "ثابت" });
  });
});

describe("Google only (A19): LinkedIn callback routes only redirect", () => {
  test("both legacy callback routes redirect to /login (source pin)", () => {
    for (const file of ["app/(auth)/linkedin-callback/page.tsx", "app/(auth)/linkedin/callback/page.tsx"]) {
      const page = src(file);
      assert.match(page, /redirect\("\/login"\)/);
      assert.doesNotMatch(page, /social-auth|linkedin\/callback\//);
    }
  });
});
