import { describe, expect, it } from "vitest";
import {
  buildClientSessionCookie,
  readClientSessionCookie,
  signClientMagicLink,
  signClientSession,
  verifyClientMagicLink,
  verifyClientSession,
} from "../../helpers/clientSessions.js";

describe("clientSessions helpers", () => {
  const secret = "client-auth-secret-for-tests";

  it("signs and verifies a client session JWT", () => {
    const token = signClientSession(
      {
        clientId: "client-123",
        email: "client@example.com",
      },
      { secret, expiresInDays: 7 }
    );

    const claims = verifyClientSession(token, { secret });

    expect(claims.sub).toBe("client-123");
    expect(claims.email).toBe("client@example.com");
    expect(claims.type).toBe("client_session");
  });

  it("rejects expired client session JWTs", () => {
    const token = signClientSession(
      {
        clientId: "client-123",
        email: "client@example.com",
      },
      { secret, expiresInDays: -1 }
    );

    expect(() => verifyClientSession(token, { secret })).toThrow(/expired/i);
  });

  it("extracts the configured client cookie from the request", () => {
    const cookie = buildClientSessionCookie("signed-token", {
      cookieDomain: "clients.xtablo.com",
      cookieName: "xtablo_client_session",
      maxAgeSeconds: 7 * 24 * 60 * 60,
    });

    const token = readClientSessionCookie(`foo=bar; xtablo_client_session=signed-token; ${cookie}`, {
      cookieName: "xtablo_client_session",
    });

    expect(token).toBe("signed-token");
  });

  it("signs magic-link JWTs with jti and expiry claims", () => {
    const token = signClientMagicLink(
      {
        clientId: "client-123",
        email: "client@example.com",
        jti: "magic-link-jti-1",
        purpose: "invite",
        redirectTo: "/tablo/test_tablo_owner_private",
      },
      { secret, expiresInMinutes: 30 }
    );

    const claims = verifyClientMagicLink(token, { secret });

    expect(claims.sub).toBe("client-123");
    expect(claims.email).toBe("client@example.com");
    expect(claims.jti).toBe("magic-link-jti-1");
    expect(claims.purpose).toBe("invite");
    expect(claims.redirect_to).toBe("/tablo/test_tablo_owner_private");
  });
});
