/**
 * BE-160 — the Google profile is read out of the GIS ID token, and the token
 * itself must travel as `social_token`: `/social-auth/` verifies nothing else.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { socialProfileFromGoogleCredential } from "@/lib/auth/google";

const jwt = (claims: Record<string, unknown>) =>
  [
    Buffer.from(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString("base64url"),
    Buffer.from(JSON.stringify(claims), "utf8").toString("base64url"),
    "signature",
  ].join(".");

describe("socialProfileFromGoogleCredential", () => {
  test("maps the ID token claims and keeps the token as social_token", () => {
    const credential = jwt({
      sub: "1234",
      email: "noor@example.test",
      given_name: "Noor",
      family_name: "Al-Sabah",
      picture: "https://lh3.example.test/a.jpg",
    });
    assert.deepEqual(socialProfileFromGoogleCredential(credential), {
      email: "noor@example.test",
      first_name: "Noor",
      last_name: "Al-Sabah",
      social_media_id: "1234",
      social_media_provider: "google",
      social_profile_pic_url: "https://lh3.example.test/a.jpg",
      social_token: credential,
    });
  });

  test("decodes UTF-8 names (Arabic) rather than Latin-1 bytes", () => {
    const profile = socialProfileFromGoogleCredential(
      jwt({ sub: "1", email: "a@example.test", given_name: "نور" })
    );
    assert.equal(profile?.first_name, "نور");
  });

  test("absent claims become absent, never empty strings", () => {
    const profile = socialProfileFromGoogleCredential(
      jwt({ sub: "1", email: "a@example.test" })
    );
    assert.equal(profile?.first_name, undefined);
    assert.equal(profile?.social_profile_pic_url, undefined);
  });

  test("no email or an unreadable token is no profile", () => {
    assert.equal(socialProfileFromGoogleCredential(jwt({ sub: "1" })), null);
    assert.equal(socialProfileFromGoogleCredential("not-a-jwt"), null);
    assert.equal(socialProfileFromGoogleCredential("a.%%%.c"), null);
    assert.equal(socialProfileFromGoogleCredential(undefined), null);
  });
});
