// 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";
import { loginWithMSW } from "../../helpers";

test.describe("Create an Account", () => {
  test.beforeEach(async ({ page, context }) => {
    await loginWithMSW(context);
    await page.goto("/account-admin");
    await expect(page.getByText("Test Admin").first()).toBeVisible();
    // Override: new usernames should return 404 (account doesn't exist yet)
    await page.evaluate(() => {
      const { http, HttpResponse } = window.__msw__;
      window.__mswWorker__.use(
        http.get("/api/users/:username", ({ params }) => {
          if ((params.username as string).startsWith("unit-test-")) {
            return HttpResponse.json(
              { detail: "Not found" },
              { status: 404 },
            );
          }
        }),
      );
    });
  });

  test("Create a new account with admin role; should show saved message.", async ({
    page,
  }) => {
    await page.getByRole("button", { name: "Create New" }).click();

    await page.locator("#input_account_field").fill("unit-test-0001");
    await page.locator("#input_name_field").fill("unit-test-0001");
    await page.locator("#input_first_pwd").fill("aaaaaa");
    await page
      .locator(".checkbox-and-text")
      .first()
      .locator("div")
      .first()
      .click();

    await expect(
      page.getByRole("button", { name: "Confirm" }),
    ).toBeVisible();
    await expect(
      page.getByRole("button", { name: "Confirm" }),
    ).toBeEnabled();
    await page.getByRole("button", { name: "Confirm" }).click();
    await expect(page.getByText("Account added")).toBeVisible();
  });

  test("Confirm button is disabled when required fields are empty.", async ({
    page,
  }) => {
    await page.getByRole("button", { name: "Create New" }).click();
    await page.locator("#input_account_field").fill("test");
    await expect(
      page.getByRole("button", { name: "Confirm" }),
    ).toBeDisabled();
  });
});
