// 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";

const MSG_ACCOUNT_NOT_UNIQUE = "Account has already been registered.";

test.describe("Account duplication check.", () => {
  test.beforeEach(async ({ page, context }) => {
    await loginWithMSW(context);
    await page.goto("/account-admin");
    await expect(page.getByText("Test Admin").first()).toBeVisible();
  });

  test("When an account already exists, show error message on confirm.", async ({
    page,
  }) => {
    const testAccountName = "000000";

    // First creation: account doesn't exist yet - override via MSW
    await page.evaluate(() => {
      const { http, HttpResponse } = window.__msw__;
      window.__mswWorker__.use(
        http.get("/api/users/000000", () =>
          HttpResponse.json(
            { detail: "Not found" },
            { status: 404 },
          ),
        ),
      );
    });

    await page.getByRole("button", { name: "Create New" }).click();
    await page.locator("#input_account_field").fill(testAccountName);
    await page.locator("#input_name_field").fill(testAccountName);
    await page.locator("#input_first_pwd").fill(testAccountName);
    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();

    // Second creation: now account exists - override to return 200 via MSW
    await page.evaluate(() => {
      const { http, HttpResponse } = window.__msw__;
      window.__mswWorker__.use(
        http.get("/api/users/000000", () =>
          HttpResponse.json({
            username: "000000",
            name: "000000",
            is_admin: false,
            is_active: true,
            roles: [],
          }),
        ),
      );
    });

    await page.getByRole("button", { name: "Create New" }).click();
    await page.locator("#input_account_field").fill(testAccountName);
    await page.locator("#input_name_field").fill(testAccountName);
    await page.locator("#input_first_pwd").fill(testAccountName);
    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(MSG_ACCOUNT_NOT_UNIQUE)).toBeVisible();
  });
});
