import { type Page, expect, test } from "@playwright/test";

async function stubOidcAuthorization(page: Page) {
  let authorizationURL = "";

  await page.route(
    "http://localhost:5000/oidc/.well-known/openid-configuration",
    async (route) => {
      await route.fulfill({
        json: {
          issuer: "http://localhost:5000/oidc",
          authorization_endpoint: "http://localhost:5000/oidc/oauth2/auth",
          token_endpoint: "http://localhost:5000/oidc/oauth2/token",
          jwks_uri: "http://localhost:5000/oidc/.well-known/jwks.json",
          userinfo_endpoint: "http://localhost:5000/oidc/userinfo",
        },
        headers: { "Access-Control-Allow-Origin": "*" },
      });
    },
  );

  await page.route(
    "http://localhost:5000/oidc/oauth2/auth**",
    async (route) => {
      authorizationURL = route.request().url();
      await route.fulfill({
        contentType: "text/html",
        body: "<!doctype html><title>Authorization captured</title>",
      });
    },
  );

  return {
    authorizationURL: () => authorizationURL,
  };
}

test("orgfront login waits for explicit auto parameter", async ({ page }) => {
  const oidc = await stubOidcAuthorization(page);

  await page.goto("/login");
  await page.waitForTimeout(500);

  expect(oidc.authorizationURL()).toBe("");
});

test("orgfront login auto parameter starts OIDC authorization", async ({
  page,
}) => {
  const oidc = await stubOidcAuthorization(page);

  await page.goto("/login?auto=1&returnTo=%2Fpicker");

  await expect.poll(oidc.authorizationURL).toContain("/oauth2/auth");

  const parsed = new URL(oidc.authorizationURL());
  expect(parsed.searchParams.get("client_id")).toBe("orgfront");
  expect(parsed.searchParams.get("redirect_uri")).toBe(
    "http://127.0.0.1:4175/auth/callback",
  );
  expect(parsed.searchParams.get("response_type")).toBe("code");
  expect(parsed.searchParams.get("scope") ?? "").toContain("openid");
});

test("orgfront login can opt out of default OIDC authorization", async ({
  page,
}) => {
  const oidc = await stubOidcAuthorization(page);

  await page.goto("/login?auto=0");
  await page.waitForTimeout(500);

  expect(oidc.authorizationURL()).toBe("");
});
