/**
 * Reading a session out of an auth response.
 *
 * These exist because of a defect that shipped: `useLoginForm`'s password path
 * read `response.data.data` while its social path read `response.data`, in the
 * same file. `loginRequest` already unwraps the axios response and returns the
 * envelope, so the password path handed `setUser` an `undefined` — the success
 * toast fired, the router pushed, and `ProtectedRoute` bounced straight back
 * to `/login`. Nothing threw and nothing was logged.
 *
 * The first case below is that exact shape.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import {
  authTokenFromAuthResponse,
  otpTokenFromResponse,
  userFromAuthResponse,
} from "@/features/auth/authSession";
import type { LoginResponseRecord, VerifyOtpRecord } from "@/features/auth/authRecords";
import type { ApiResponse } from "@/lib/api/types";

const userRecord = (
  overrides: Partial<LoginResponseRecord> = {}
): LoginResponseRecord => ({
  id: 7,
  first_name: "Noor",
  last_name: "Al-Sabah",
  email: "noor@example.com",
  profile_pic: null,
  social_media_id: null,
  social_media_provider: null,
  user_type: "volunteer",
  manual_id: "V-0007",
  is_new_user: false,
  is_verified: true,
  is_banned: false,
  receive_reminder_emails: true,
  do_not_disturb: false,
  is_trainer: false,
  trainer_status: null,
  trainer_types: [],
  show_real_name: true,
  auth_token: "5|plain-text-sanctum-token",
  ...overrides,
});

/** The success envelope `ApiResponse::success()` builds. */
const envelope = (
  data: LoginResponseRecord | null
): ApiResponse<LoginResponseRecord> =>
  ({
    key: "success",
    msg: "Login successful.",
    code: 200,
    response_status: { error: false, validation_errors: [] },
    data,
  }) as unknown as ApiResponse<LoginResponseRecord>;

/**
 * `POST /login/`'s envelope, which nests once more than every other endpoint:
 * `ApiResponse::success(['data' => $payload], …)` at `AuthController:138`,
 * against `ApiResponse::success($payload, …)` for social sign-in at `:616`.
 * It is the only `['data' =>` in the controllers.
 */
const loginEnvelope = (
  data: LoginResponseRecord | null
): ApiResponse<LoginResponseRecord> =>
  ({
    key: "success",
    msg: "Login successful.",
    code: 200,
    response_status: { error: false, validation_errors: [] },
    data: { data },
  }) as unknown as ApiResponse<LoginResponseRecord>;

describe("userFromAuthResponse — the password sign-in envelope", () => {
  /*
   * The shape that was failing in the browser: a 200 with a real token, read
   * as "no session", so the form showed its own «Login failed. Please try
   * again.» while Postman showed the token sitting right there. Password
   * sign-in could not complete at all.
   */
  test("the user is found through POST /login/'s extra level", () => {
    const user = userFromAuthResponse(loginEnvelope(userRecord()));
    assert.equal(user?.id, 7);
    assert.equal(user?.auth_token, "5|plain-text-sanctum-token");
  });

  test("the token comes back from the nested shape too", () => {
    assert.equal(
      authTokenFromAuthResponse(loginEnvelope(userRecord())),
      "5|plain-text-sanctum-token"
    );
  });

  test("a nested record with no token is still no session", () => {
    const tokenless = { ...userRecord(), auth_token: "" };
    assert.equal(userFromAuthResponse(loginEnvelope(tokenless)), null);
  });

  test("an empty nesting is no session", () => {
    assert.equal(userFromAuthResponse(loginEnvelope(null)), null);
  });

  /* The social shape must keep working unchanged — it is the one the reader
     was written for, and the one the extra level must not shadow. */
  test("the social envelope is unaffected", () => {
    const user = userFromAuthResponse(envelope(userRecord()));
    assert.equal(user?.id, 7);
  });

  /* A record carrying its own token is never looked past, whatever else it
     happens to hold under a `data` key. */
  test("an outer token wins over anything nested", () => {
    const outer = userRecord({ auth_token: "outer-token" });
    const confusing = {
      ...outer,
      data: userRecord({ auth_token: "inner-token" }),
    } as unknown as LoginResponseRecord;
    assert.equal(userFromAuthResponse(envelope(confusing))?.auth_token, "outer-token");
  });
});

describe("userFromAuthResponse", () => {
  test("reads the user record from the envelope's data", () => {
    const user = userFromAuthResponse(envelope(userRecord()));
    assert.equal(user?.id, 7);
    assert.equal(user?.auth_token, "5|plain-text-sanctum-token");
  });

  test("the shipped defect: the envelope is unwrapped once, not twice", () => {
    /*
     * The old password path evaluated `response.data.data`. Reading the result
     * of this function the same way is what that was, and it has to be
     * `undefined` — if a future refactor ever makes `data.data` meaningful,
     * this assertion is the warning.
     */
    const asShipped = (envelope(userRecord()).data as unknown as {
      data?: unknown;
    }).data;
    assert.equal(asShipped, undefined);

    // The reader gets the record that `.data.data` missed.
    assert.notEqual(userFromAuthResponse(envelope(userRecord())), null);
  });

  test("a success envelope with no payload is not a session", () => {
    assert.equal(userFromAuthResponse(envelope(null)), null);
  });

  test("a record with no token is not a session", () => {
    /*
     * The case `isApiSuccess()` cannot catch: `key === "success"` and
     * `response_status.error === false`, but nothing to authenticate with.
     * Four call sites used to pass this straight to `setUser`, which would
     * leave the request interceptor sending no `Authorization` header while
     * the UI believed it was signed in.
     */
    const withoutToken = userRecord();
    delete (withoutToken as Partial<LoginResponseRecord>).auth_token;
    assert.equal(userFromAuthResponse(envelope(withoutToken)), null);
  });

  test("an empty-string token is not a session either", () => {
    assert.equal(
      userFromAuthResponse(envelope(userRecord({ auth_token: "" }))),
      null
    );
  });

  test("a missing or null envelope answers null rather than throwing", () => {
    assert.equal(userFromAuthResponse(undefined), null);
    assert.equal(userFromAuthResponse(null), null);
  });
});

describe("the credential key differs by endpoint", () => {
  test("/login/ and /social-auth/ carry `auth_token`", () => {
    assert.equal(
      authTokenFromAuthResponse(envelope(userRecord())),
      "5|plain-text-sanctum-token"
    );
  });

  test("/verify_otp_or_token/ carries `token`, under a different name", () => {
    const otp = {
      key: "success",
      msg: "ok",
      code: 200,
      response_status: { error: false, validation_errors: [] },
      data: { token: "one-shot-reset-token", user_id: 7 } satisfies VerifyOtpRecord,
    } as unknown as ApiResponse<VerifyOtpRecord>;

    assert.equal(otpTokenFromResponse(otp), "one-shot-reset-token");

    /*
     * And it is not reachable through the session reader. This is the point of
     * keeping two functions: with `type: "password"` that string is a
     * `password_reset_tokens` row, and putting it in `authStore.user
     * .auth_token` would send a single-use reset authorisation as the
     * credential on every subsequent request.
     */
    assert.equal(
      authTokenFromAuthResponse(
        otp as unknown as ApiResponse<LoginResponseRecord>
      ),
      null
    );
  });

  test("a login payload has no `token` key to be read by mistake", () => {
    const login = userRecord() as unknown as Record<string, unknown>;
    assert.equal("token" in login, false);
    assert.equal("auth_token" in login, true);
  });

  test("/register/ issues no credential at all", () => {
    /*
     * `WebsiteRegisterUserResource` is five keys and no token — registering
     * does not sign the account in, the flow continues through OTP and then
     * login. Asserted as a shape so a wrapper typed to return a session here
     * would have to change this test.
     */
    const registered = {
      key: "success",
      msg: "ok",
      code: 201,
      response_status: { error: false, validation_errors: [] },
      data: {
        id: 7,
        email: "noor@example.com",
        first_name: "Noor",
        last_name: "Al-Sabah",
        user_type: "volunteer",
      },
    } as unknown as ApiResponse<LoginResponseRecord>;

    assert.equal(userFromAuthResponse(registered), null);
  });
});
