// The Lucia project.
// Copyright 2026-2026 DSP, inc.  All rights reserved.
// Authors:
//   imacat.yang@dsp.im (imacat), 2026/03/22

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

test.describe("Paste URL login redirect", () => {
  test("After login with return-to param, redirects to the remembered page", async ({
    page,
    context,
  }) => {
    // Visit login page with a return-to query param (base64-encoded URL)
    const targetUrl =
      "http://localhost:4173/discover/conformance/log/1/conformance";
    const encodedUrl = btoa(targetUrl);
    await page.goto(`/login?return-to=${encodedUrl}`);

    // Fill in login form
    await page.locator("#account").fill("testadmin");
    await page.locator("#password").fill("password123");
    await page.locator("form").evaluate((form) =>
      (form as HTMLFormElement).submit(),
    );

    // After login, the app should attempt to redirect to the return-to URL.
    // Verify login succeeded by checking the login form is gone.
    await expect(page.locator("#login_btn_main_btn")).not.toBeVisible();
  });

  test("Login without return-to param redirects to /files", async ({
    page,
  }) => {
    await page.goto("/login");

    await page.locator("#account").fill("testadmin");
    await page.locator("#password").fill("password123");
    await page.locator("#login_btn_main_btn").click();

    await expect(page).toHaveURL(/\/files/, { timeout: 10000 });
  });

  test("Unauthenticated user cannot access inner pages", async ({
    page,
  }) => {
    // Visit login first to load the app + MSW
    await page.goto("/login");
    await expect(page.locator("#login_btn_main_btn")).toBeVisible();
    // Override my-account to return 401 (simulate logged-out state) via MSW
    await page.evaluate(() => {
      const { http, HttpResponse } = window.__msw__;
      window.__mswWorker__.use(
        http.get("/api/my-account", () =>
          HttpResponse.json(
            { detail: "Not authenticated" },
            { status: 401 },
          ),
        ),
      );
    });

    await page.goto("/files");

    // Should be redirected to login page
    await expect(page).toHaveURL(/\/login/);
    await expect(page.locator("#account")).toBeVisible();
    await expect(page.locator("#password")).toBeVisible();
  });
});
