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 { uc29DefaultData, uc29DefaultUrl } from "../uc29.default.data";

const BASE_URL = process.env.BASE_URL!;

const assertRelatedModalHeaders = async (targetPage: Page) => {
  const modalContent = targetPage.locator(".ant-modal-content:visible").last();
  await targetPage.waitForTimeout(TIMEOUT.DATA_LOADING);
  const searchInput = modalContent.locator(
    'input[placeholder="Nhập tên tài liệu, mã tài liệu"]',
  );

  const rows = modalContent.locator(".ant-table-row.ant-table-row-level-0");

  await searchInput.fill("!@#$%^&*()_+{}|:<>?\\\\////");
  await searchInput.press("Enter");
  await targetPage.waitForTimeout(10000);

  await expect(rows, {
    message:
      "Lỗi: Tìm bằng ký tự đặc biệt phải không hiển thị kết quả nào trong popup",
  }).toHaveCount(0);

  await searchInput.fill("LEWIND TEST DOCUMENT N60ct|-|@|\\|G");
  await searchInput.press("Enter");
  await targetPage.waitForTimeout(10000);

  await expect(rows.first(), {
    message:
      'Lỗi: Không tìm thấy kết quả cho text "LEWIND TEST DOCUMENT N60ct|-|@|\\|G"',
  }).toBeVisible({ timeout: TIMEOUT.DATA_LOADING });
};

const runTest = async (page: Page) => {
  const pw = new PW(page);

  await test.step("1. Truy cập màn hình Kho tài liệu", async () => {
    await page.goto(`${BASE_URL}${uc29DefaultUrl}`);
  });
  await test.step("2. Chọn nút Tạo mới", async () => {
    await pw.isVisible("btn-create-hstl", TIMEOUT.PAGE_LOADING);
    await pw.wait(TIMEOUT.HARD_WAITING);
    await pw.clickButton("btn-create-hstl");
  });
  await test.step("3. Kiểm tra nút bấm thêm Thông tin liên quan ở màn Tạo mới hồ sơ", async () => {
    const parent = page
      .locator('[data-testid="btn-add-related-ecm"]')
      .locator("..");
    await parent.locator(".ant-dropdown-trigger").hover();
    await page.getByText("Tài liệu liên quan").click();
    await expect(page.getByText("Tìm tài liệu liên quan"), {
      message:
        "Lỗi: Pop-up tìm tài liệu liên quan không hiển thị sau khi bấm chọn",
    }).toBeVisible({
      timeout: TIMEOUT.DATA_LOADING,
    });
    await pw.wait(TIMEOUT.DATA_LOADING);
    await assertRelatedModalHeaders(page);
  });

  //   await test.step("6. Kiểm tra nút bấm thêm Thông tin liên quan ở")
};

test(
  "UC29 1.1.2.6.75 - [Text-box tìm tài liệu] Không có kết quả với ký tự đặc biệt, sau đó tìm thấy kết quả đúng - Thủ thư" +
    ACCOUNT.LIBRARIAN,
  async ({ librarian }) => {
    await runTest(librarian);
  },
);
test(
  "UC29 1.1.2.6.75 - [Text-box tìm tài liệu] Không có kết quả với ký tự đặc biệt, sau đó tìm thấy kết quả đúng - Admin" +
    ACCOUNT.ADMIN,
  async ({ admin }) => {
    await runTest(admin);
  },
);
