import type { ApiResponse } from "@/lib/api/types";
import type { LoginResponseRecord, VerifyOtpRecord } from "./authRecords";

/**
 * Reading a signed-in user out of an auth response — in one place, because the
 * call sites that did it did not agree, and neither do the endpoints.
 *
 * `loginRequest` and `passSocialInfoRequest` already unwrap the axios
 * response: they return `response.data`, the **envelope**
 * (`{ key, msg, code, response_status, data }`).
 *
 * **The two sign-in endpoints then disagree about what is inside `data`.** In
 * the same controller, twenty lines apart in effect:
 *
 * ```php
 * // POST /login/        — AuthController:138
 * return ApiResponse::success(['data' => $payload], 'Login successful.', …);
 * // POST /social-auth/  — AuthController:616
 * return ApiResponse::success($payload, 'Login successful. Welcome!', …);
 * ```
 *
 * `ApiResponse::make()` does not unwrap, so a password sign-in puts the user
 * at `envelope.data.data` while a social one puts it at `envelope.data`. It is
 * the **only** endpoint in the API that nests twice — grepping the controllers
 * for `['data' =>` returns that one line — and it has been that way since the
 * project's first commit.
 *
 * So this reads `envelope.data`, and accepts one further `data` when that is
 * where the token turns out to be. Tolerating both is deliberate rather than
 * lazy: the mobile client reads the nested shape today, so the backend cannot
 * simply flatten it without breaking that, and this way we are correct either
 * way it is resolved.
 *
 * The history is worth keeping, because the correction went the wrong way
 * once: `useLoginForm` read `response.data.data` on its password path and
 * `response.data` on its social path. Both were replaced with
 * `envelope.data` — which fixed the social path and left the password one
 * handing `setUser` a record with no token. The symptom was a toast reading
 * «Login failed. Please try again.» on correct credentials, with a 200 and a
 * valid token in the response the whole time.
 */

/**
 * The user record, or `null` when the envelope carries none.
 *
 * `null` rather than `undefined` on purpose: `authStore.setUser` takes a
 * `User`, so the one thing a caller must not do is hand it the absent case
 * silently. A `null` has to be dealt with.
 */
export function userFromAuthResponse(
  envelope:
    | ApiResponse<LoginResponseRecord | NestedLoginRecord>
    | null
    | undefined
): LoginResponseRecord | null {
  const body = envelope?.data;
  /* `POST /login/`'s extra level, and only if the token is really down there:
     a record that carries its own `auth_token` is never looked past. */
  const user = hasToken(body)
    ? body
    : hasToken((body as NestedLoginRecord | null | undefined)?.data)
      ? ((body as NestedLoginRecord).data as LoginResponseRecord)
      : null;

  return user;
}

/** `POST /login/`'s shape: the record one level further down. */
type NestedLoginRecord = { data?: LoginResponseRecord | null };

/**
 * A truthiness test is not enough — `data` is `null` on the endpoints that
 * answer with no body, and `{}` would be a record with no token. The token is
 * the one key that makes this a *session* rather than a profile, and it is
 * also what tells the two envelope shapes apart.
 */
function hasToken(value: unknown): value is LoginResponseRecord {
  if (!value || typeof value !== "object") return false;
  const token = (value as { auth_token?: unknown }).auth_token;
  return typeof token === "string" && token !== "";
}

/**
 * The credential from a sign-in response.
 *
 * Named for the key it reads. `POST /login/` and `POST /social-auth/` merge
 * **`auth_token`** onto the payload (`AuthController.php:136` and `:614`),
 * and that is the key `lib/api/client.ts` sends as `Authorization: Token …`.
 */
export function authTokenFromAuthResponse(
  envelope:
    | ApiResponse<LoginResponseRecord | NestedLoginRecord>
    | null
    | undefined
): string | null {
  return userFromAuthResponse(envelope)?.auth_token ?? null;
}

/**
 * The one-shot token from `POST /verify_otp_or_token/`.
 *
 * Deliberately a *different* function from the two above, because the key is a
 * different key (**`token`**, not `auth_token`) holding a different kind of
 * thing. With `type: "register"` it is a Sanctum credential; with
 * `type: "password"` it is a `password_reset_tokens` row, which is what
 * `/reset-password?token=` carries in the URL.
 *
 * Neither is a session, and neither may be passed to `setUser` — a reset token
 * in `authStore.user.auth_token` would be sent as a credential on every
 * subsequent request. Returning them through a separate function with no
 * `auth_token` in sight is what keeps the two from being confused.
 */
export function otpTokenFromResponse(
  envelope: ApiResponse<VerifyOtpRecord> | null | undefined
): string | null {
  const token = envelope?.data?.token;
  return typeof token === "string" && token !== "" ? token : null;
}
