import { describe, test } from "node:test";
import assert from "node:assert/strict";

import {
  getApiErrorMessage,
  getApiErrorMessages,
  getApiFieldErrors,
  getApiReasonCode,
} from "@/lib/api/errors";

/**
 * S-ACC-1 — `ApiRefusal::respond()` (backend 409e2f4, app/Support/ApiRefusal.php)
 * answers `msg` = the localized text and copies the stable code into BOTH
 * `data.reason_code` and `response_status.validation_errors.reason_code`.
 * The error helpers read the bag first, so the raw code ("account_deactivated")
 * was what sign-in and every other ApiRefusal screen showed.
 */
const refusal = (code: string, msg: string, data: Record<string, unknown> = {}) => ({
  response: {
    status: 403,
    data: {
      key: "fail",
      msg,
      code: 403,
      response_status: { error: true, validation_errors: { reason_code: [code] } },
      data: { reason_code: code, ...data },
    },
  },
});

describe("S-ACC-1 — ApiRefusal reason codes are not shown as messages", () => {
  const deactivated = refusal(
    "account_deactivated",
    "تم تعطيل هذا الحساب من قبل الإدارة. لإعادة تفعيله يرجى التواصل عبر forsa@joinforsa.net.",
    { contact_email: "forsa@joinforsa.net" }
  );

  test("the localized msg is the message, not the code", () => {
    assert.equal(getApiErrorMessage(deactivated, "ar"), deactivated.response.data.msg);
    assert.deepEqual(getApiErrorMessages(deactivated, "ar"), [deactivated.response.data.msg]);
  });

  test("reason_code is not reported as a field error", () => {
    assert.deepEqual(getApiFieldErrors(deactivated, "ar"), {});
  });

  test("the code stays readable for branching", () => {
    assert.equal(getApiReasonCode(deactivated), "account_deactivated");
    assert.equal(getApiReasonCode({ response: { data: { msg: "x" } } }), null);
    assert.equal(getApiReasonCode(null), null);
  });

  test("real field errors next to a reason code are kept", () => {
    const mixed = refusal("registration_replaced", "Please sign up again.");
    (mixed.response.data.response_status.validation_errors as Record<string, string[]>).email = ["taken"];
    assert.deepEqual(getApiFieldErrors(mixed, "en"), { email: "taken" });
    assert.equal(getApiErrorMessage(mixed, "en"), "taken");
  });

  test("legacy { en, ar } field errors are unaffected", () => {
    const legacy = { response: { data: { errors: { email: { en: "User not found.", ar: "المستخدم غير موجود." } } } } };
    assert.equal(getApiErrorMessage(legacy, "ar"), "المستخدم غير موجود.");
  });
});
