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

async function seedTokenLogin(page: Page): Promise<void> {
  await page.addInitScript(() => {
    window.localStorage.setItem("baron_auth_token", "e30.e30.e30");
    window.localStorage.setItem("baron_auth_provider", "ory");
    window.localStorage.removeItem("baron_auth_cookie_mode");
    window.localStorage.removeItem("baron_auth_pending_provider");
  });
}

async function mockInventoryApis(page: Page): Promise<void> {
  await page.route("**/api/v1/**", async (route: Route) => {
    const requestUrl = new URL(route.request().url());
    const path = requestUrl.pathname;
    const method = route.request().method().toUpperCase();

    if (path.endsWith("/api/v1/user/me")) {
      const authHeader = route.request().headers().authorization ?? "";
      if (authHeader.startsWith("Bearer ")) {
        await route.fulfill({
          status: 200,
          contentType: "application/json",
          body: JSON.stringify({
            id: "e2e-user",
            email: "e2e@example.com",
            name: "E2E User",
            phone: "+821012341234",
            department: "QA",
            affiliationType: "employee",
            companyCode: "BARON",
            tenant: {
              id: "tenant-1",
              name: "Baron",
              slug: "baron",
              description: "E2E tenant",
            },
          }),
        });
        return;
      }

      await route.fulfill({
        status: 401,
        contentType: "application/json",
        body: JSON.stringify({ error: "unauthorized" }),
      });
      return;
    }

    if (path.endsWith("/api/v1/user/rp/linked")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ items: [] }),
      });
      return;
    }

    if (path.endsWith("/api/v1/audit/auth/timeline")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ items: [], next_cursor: "" }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/password/policy")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          minLength: 12,
          minCharacterTypes: 3,
          lowercase: true,
          uppercase: true,
          number: true,
          nonAlphanumeric: true,
        }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/magic-link/verify")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ status: "approved" }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/login/code/verify")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ status: "approved" }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/login/code/verify-short")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ status: "approved" }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/consent") && method === "GET") {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          client: {
            client_name: "E2E Client",
            client_id: "e2e-client",
          },
          requested_scope: ["openid"],
          scope_details: {
            openid: {
              description: "OpenID",
              mandatory: true,
            },
          },
        }),
      });
      return;
    }

    if (path.endsWith("/api/v1/auth/qr/approve")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ ok: true }),
      });
      return;
    }

    if (path.endsWith("/api/v1/client-log")) {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ ok: true }),
      });
      return;
    }

    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({}),
    });
  });
}

test.describe("UserFront WASM route inventory (unauth)", () => {
  test.beforeEach(async ({ page }) => {
    await mockInventoryApis(page);
  });

  test("route: /", async ({ page }) => {
    await page.goto("/");
    await expect(page).toHaveURL(/\/(ko|en)\/signin(?:\?.*)?$/);
  });

  test("route: /ko", async ({ page }) => {
    await page.goto("/ko");
    await expect(page).toHaveURL(/\/ko\/signin(?:\?.*)?$/);
  });

  test("route: /ko/dashboard", async ({ page }) => {
    await page.goto("/ko/dashboard");
    await expect(page).toHaveURL(/\/ko\/signin$/);
  });

  test("route: /ko/profile", async ({ page }) => {
    await page.goto("/ko/profile");
    await expect(page).toHaveURL(/\/ko\/signin$/);
  });

  test("route: /ko/admin/users", async ({ page }) => {
    await page.goto("/ko/admin/users");
    await expect(page).toHaveURL(/\/ko\/signin$/);
  });

  test("route: /ko/scan", async ({ page }) => {
    await page.goto("/ko/scan");
    await expect(page).toHaveURL(/\/ko\/signin$/);
  });

  test("route: /ko/signin", async ({ page }) => {
    await page.goto("/ko/signin");
    await expect(page).toHaveURL(/\/ko\/signin$/);
  });

  test("route: /ko/login", async ({ page }) => {
    await page.goto("/ko/login");
    await expect(page).toHaveURL(/\/ko\/login$/);
  });

  test("route: /ko/signup", async ({ page }) => {
    await page.goto("/ko/signup");
    await expect(page).toHaveURL(/\/ko\/signup$/);
  });

  test("route: /ko/registration", async ({ page }) => {
    await page.goto("/ko/registration");
    await expect(page).toHaveURL(/\/ko\/registration$/);
  });

  test("route: /ko/verify", async ({ page }) => {
    await page.goto("/ko/verify");
    await expect(page).toHaveURL(/\/ko\/verify$/);
  });

  test("route: /ko/verify/:token", async ({ page }) => {
    await page.goto("/ko/verify/e2e-token");
    await expect(page).toHaveURL(/\/ko\/verify\/e2e-token$/);
  });

  test("route: /ko/verification", async ({ page }) => {
    await page.goto("/ko/verification");
    await expect(page).toHaveURL(/\/ko\/verification$/);
  });

  test("route: /ko/verify-complete", async ({ page }) => {
    await page.goto("/ko/verify-complete");
    await expect(page).toHaveURL(/\/ko\/verify-complete$/);
  });

  test("route: /ko/l/:shortCode", async ({ page }) => {
    await page.goto("/ko/l/AB123456");
    await expect(page).toHaveURL(/\/ko\/l\/AB123456$/);
  });

  test("route: /ko/forgot-password", async ({ page }) => {
    await page.goto("/ko/forgot-password");
    await expect(page).toHaveURL(/\/ko\/forgot-password$/);
  });

  test("route: /ko/recovery", async ({ page }) => {
    await page.goto("/ko/recovery");
    await expect(page).toHaveURL(/\/ko\/recovery$/);
  });

  test("route: /ko/reset-password", async ({ page }) => {
    await page.goto("/ko/reset-password?token=e2e-reset-token");
    await expect(page).toHaveURL(
      /\/ko\/reset-password\?token=e2e-reset-token$/,
    );
  });

  test("route: /ko/error", async ({ page }) => {
    await page.goto("/ko/error?error=invalid_request");
    await expect(page).toHaveURL(/\/ko\/error\?error=invalid_request$/);
  });

  test("route: /ko/settings", async ({ page }) => {
    await page.goto("/ko/settings");
    await expect(page).toHaveURL(/\/ko\/settings$/);
  });

  test("route: /ko/consent (missing challenge)", async ({ page }) => {
    await page.goto("/ko/consent");
    await expect(page).toHaveURL(/\/ko\/consent$/);
  });

  test("route: /ko/consent?consent_challenge=...", async ({ page }) => {
    await page.goto("/ko/consent?consent_challenge=e2e-consent");
    await expect(page).toHaveURL(
      /\/ko\/consent\?consent_challenge=e2e-consent$/,
    );
  });

  test("route: /ko/approve?ref=...", async ({ page }) => {
    await page.goto("/ko/approve?ref=e2e-ref");
    await expect(page).toHaveURL(/\/ko\/signin\?notice=qr_login_required$/);
  });

  test("route: /ko/ql/:ref", async ({ page }) => {
    await page.goto("/ko/ql/e2e-ref");
    await expect(page).toHaveURL(/\/ko\/signin\?notice=qr_login_required$/);
  });
});

test.describe("UserFront WASM route inventory (authed)", () => {
  test.beforeEach(async ({ page }) => {
    await seedTokenLogin(page);
    await mockInventoryApis(page);
  });

  test("route: /ko -> /ko/dashboard", async ({ page }) => {
    await page.goto("/ko");
    await expect(page).toHaveURL(/\/ko\/dashboard$/);
  });

  test("route: /ko/dashboard", async ({ page }) => {
    await page.goto("/ko/dashboard");
    await expect(page).toHaveURL(/\/ko\/dashboard$/);
  });

  test("route: /ko/profile", async ({ page }) => {
    await page.goto("/ko/profile");
    await expect(page).toHaveURL(/\/ko\/profile$/);
  });

  test("route: /ko/admin/users", async ({ page }) => {
    await page.goto("/ko/admin/users");
    await expect(page).toHaveURL(/\/ko\/admin\/users$/);
  });

  test("route: /ko/scan", async ({ page }) => {
    await page.goto("/ko/scan");
    await expect(page).toHaveURL(/\/ko\/scan$/);
  });

  test("route: /ko/approve?ref=... -> /ko/dashboard", async ({
    page,
  }, testInfo) => {
    await page.goto("/ko/approve?ref=e2e-ref");
    await expect(page).toHaveURL(/\/ko\/dashboard$/, {
      timeout: testInfo.project.name === "webkit-desktop" ? 15_000 : 5_000,
    });
  });

  test("route: /ko/ql/:ref -> /ko/dashboard", async ({ page }, testInfo) => {
    await page.goto("/ko/ql/e2e-ref");
    await expect(page).toHaveURL(/\/ko\/dashboard$/, {
      timeout: testInfo.project.name === "webkit-desktop" ? 15_000 : 5_000,
    });
  });
});
