import { Page } from "@playwright/test";
import { test, expect, ACCOUNT } from "../../../src/fixture/base-test";
import { TIMEOUT } from "../../../src/constant/timeout";
import { PW } from "../../../src/utils/PW";
import { uc77DefaultData, uc77DefaultUrl } from "../uc77.default.data";

const BASE_URL = process.env.BASE_URL!;

const runTest = async (
  page: Page,
  ecm05Page: Page,
  ecm06Page: Page,
  ecm04Page: Page,
  ecm07Page: Page,
  ecm08Page: Page,
) => {
  const pw = new PW(page);
  const uniqueName = `AT-UC77-85-${Date.now()}`;

  await test.step("1. Truy cập màn hình Kho tài liệu và mở form Tạo mới", async () => {
    await page.goto(`${BASE_URL}${uc77DefaultUrl}`);
    await pw.isVisible("btn-create-hstl", TIMEOUT.PAGE_LOADING);
    await pw.wait(TIMEOUT.HARD_WAITING);
    await pw.clickButton("btn-create-hstl");
  });

  await test.step("2. Điền form và gán quyền các user", async () => {
    await pw.batchInput(
      uc77DefaultData.filter(
        (o) =>
          !o.testId.startsWith("pp-multi-") &&
          o.testId !== "txt-tenHoSo" &&
          o.testId !== "btn-add-related-ecm",
      ),
      true,
    );
    await pw.inputText("txt-tenHoSo", uniqueName);
    await pw.inputPeoplePicker("pp-multi-usersRightOwner", "ecm05");
    await pw.inputPeoplePicker("pp-multi-usersRightViewers", "ecm06");
    await pw.inputPeoplePicker("pp-multi-usersRightDownload", "ecm04");
    await pw.inputPeoplePicker("pp-multi-usersRightAdd", "ecm07");
    await pw.inputPeoplePicker("pp-multi-usersRightEdit", "ecm08");
  });

  await test.step("3. Lưu hồ sơ", async () => {
    await pw.clickButton("btn-save");
    await expect(page.locator(".ant-message-success"), {
      message: "Lỗi: Tạo mới hồ sơ không thành công",
    }).toBeVisible({ timeout: TIMEOUT.ACTION_LOADING });
    await pw.wait(TIMEOUT.ACTION_LOADING);
  });

  const recordUrl = page.url();

  await test.step("5. Chuyển hồ sơ sang trạng thái Hoạt động", async () => {
    await page.goto(recordUrl);
    await pw.wait(TIMEOUT.HARD_WAITING);
    await page.getByRole("button", { name: "Chuyển Hoạt động" }).click();
    await page
      .locator(".ant-modal-confirm-btns")
      .getByRole("button", { name: "Chuyển hoạt động" })
      .click();
    await expect(page.locator(".ant-message-notice"), {
      message:
        "Lỗi: Thông báo 'Thành công' sau Chuyển hoạt động không hiển thị",
    }).toContainText("Thành công", { timeout: TIMEOUT.ACTION_LOADING });
    await pw.wait(TIMEOUT.ACTION_LOADING);
  });

  // Các vai KHÔNG phải Owner — kiểm tra sau khi hồ sơ đã Hoạt động
  const ROLE_CHECKS = [
    {
      userPage: ecm05Page,
      label: "ecm05 Owner",
      shouldSee: true,
      closeAfter: true,
    },
    {
      userPage: ecm06Page,
      label: "ecm06 Viewer",
      shouldSee: false,
      closeAfter: true,
    },
    {
      userPage: ecm04Page,
      label: "ecm04 Download",
      shouldSee: false,
      closeAfter: true,
    },
    {
      userPage: ecm07Page,
      label: "ecm07 Add",
      shouldSee: false,
      closeAfter: true,
    },
    {
      userPage: ecm08Page,
      label: "ecm08 Edit",
      shouldSee: false,
      closeAfter: true,
    },
  ];

  await test.step("6–9. Kiểm tra button 'Kiểm tra phân quyền' theo từng quyền không phải Owner (song song)", async () => {
    await Promise.all(
      ROLE_CHECKS.map(({ userPage, label, closeAfter }) =>
        test.step(`Kiểm tra [${label}]`, async () => {
          const pwUser = new PW(userPage);
          await userPage.goto(recordUrl);
          await pwUser.wait(TIMEOUT.HARD_WAITING);
          await pwUser.clickButton("lbl-tab-thongTin");
          const trigger = userPage.getByTestId("btn-more");

          const triggerVisible = await trigger.isVisible();
          if (triggerVisible) {
            await trigger.hover();
            await expect(userPage.getByTestId("btn-kiem-tra-phan-quyen"), {
              message: `[${label}] Lỗi: Vẫn hiển thị button 'Kiểm tra phân quyền'`,
            }).not.toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });
          }

          if (closeAfter) await userPage.close();
        }),
      ),
    );
  });
};

test(
  "UC77,78,80 1.2.85,86 - Kiểm tra hiển thị lựa chọn phân quyền - Admin" +
    ACCOUNT.ADMIN,
  async ({ admin, ecm05, ecm06, ecm04, ecm07, ecm08 }) => {
    await runTest(admin, ecm05, ecm06, ecm04, ecm07, ecm08);
  },
);
