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 runTest = async (page: Page) => {
  const pw = new PW(page);
  const name1 = `AT-HSTL-LINK1-${Date.now()}`;
  const name2 = `AT-HSTL-LINK2-${Date.now()}`;
  // Bỏ Owner (xử lý riêng), tên hồ sơ (đặt unique) và nút thêm liên quan
  // (chỉ thêm liên quan thủ công cho phiếu 2) khỏi batchInput.
  const baseData = uc29DefaultData.filter(
    (o) =>
      o.testId !== "pp-multi-usersRightOwner" &&
      o.testId !== "txt-tenHoSo" &&
      o.testId !== "btn-add-related-ecm",
  );

  let url1 = "";

  await test.step("1. Tạo phiếu 1 (lưu URL phiếu 1)", async () => {
    await page.goto(`${BASE_URL}${uc29DefaultUrl}`);
    await pw.isVisible("btn-create-hstl", TIMEOUT.PAGE_LOADING);
    await pw.wait(TIMEOUT.HARD_WAITING);
    await pw.clickButton("btn-create-hstl");

    await pw.batchInput(baseData, true);
    await pw.inputText("txt-tenHoSo", name1);
    await pw.inputPeoplePicker("pp-multi-usersRightOwner", "ecm05");
    await pw.clickButton("btn-save");
    await expect(page.locator(".ant-message-success"), {
      message: "Lỗi: Tạo phiếu 1 không thành công",
    }).toBeVisible({ timeout: TIMEOUT.ACTION_LOADING });

    // Sau khi lưu, form chuyển sang màn Cập nhật → lấy URL phiếu 1
    await pw.wait(TIMEOUT.ACTION_LOADING);
    url1 = page.url();

    await pw.clickButton("btn-close-modal");
    await expect(page.getByTestId("btn-close-modal")).not.toBeVisible({
      timeout: TIMEOUT.ACTION_LOADING,
    });
  });

  await test.step("2. Tạo phiếu 2, chọn phiếu 1 làm Hồ sơ liên quan", async () => {
    await pw.clickButton("btn-create-hstl");
    await pw.wait(TIMEOUT.HARD_WAITING);

    await pw.batchInput(baseData, true);
    await pw.inputText("txt-tenHoSo", name2);
    await pw.inputPeoplePicker("pp-multi-usersRightOwner", "ecm05");

    // Mở pop-up tìm hồ sơ liên quan, tìm phiếu 1 và chọn
    await pw.clickButton("btn-add-related-ecm");
    await page
      .getByText("Tìm hồ sơ liên quan")
      .waitFor({ timeout: TIMEOUT.ACTION_LOADING });

    const modalContent = page.locator(".ant-modal-content:visible").last();
    const searchInput = modalContent.locator(
      'input[placeholder="Nhập tên hồ sơ, số hồ sơ"]',
    );
    await searchInput.fill(name1);
    await searchInput.press("Enter");
    await page.waitForTimeout(10000);

    const firstRow = modalContent
      .locator(".ant-table-row.ant-table-row-level-0")
      .first();
    await expect(firstRow, {
      message: "Lỗi: Không tìm thấy phiếu 1 trong kết quả tìm hồ sơ liên quan",
    }).toContainText(name1, { timeout: TIMEOUT.DATA_LOADING });

    await firstRow.hover();
    await modalContent
      .locator(".ant-table-row.ant-table-row-level-0 .ant-checkbox-wrapper")
      .first()
      .click();
    await expect(page.getByTestId("btn-add-related"), {
      message: "Lỗi: Nút 'Thêm' không hiển thị khi đã chọn phiếu 1",
    }).toBeVisible({ timeout: TIMEOUT.CONTROL_LOADING });
    await pw.clickButton("btn-add-related");
    await pw.isVisible("related-item-table");

    // Phiếu 1 đã được thêm vào HS liên quan của phiếu 2
    const relatedRows = page
      .getByTestId("related-item-table")
      .locator(".cssMaHSTLChild");
    await expect(relatedRows, {
      message: "Lỗi: Phiếu 1 chưa được thêm vào HS liên quan của phiếu 2",
    }).toHaveCount(1);

    await pw.clickButton("btn-save");
    await expect(page.locator(".ant-message-success"), {
      message: "Lỗi: Tạo phiếu 2 không thành công",
    }).toBeVisible({ timeout: TIMEOUT.ACTION_LOADING });
    await pw.wait(TIMEOUT.ACTION_LOADING);
    await pw.clickButton("btn-close-modal");
  });

  await test.step("3. Truy cập lại phiếu 1, kiểm tra hồ sơ liên quan là phiếu 2", async () => {
    await page.goto(url1);
    await pw.wait(TIMEOUT.HARD_WAITING);
    await pw.clickButton("lbl-tab-thongTin");
    await pw.isVisible("related-item-table", TIMEOUT.DATA_LOADING);

    // Liên kết 2 chiều: phiếu 1 (ban đầu trống) giờ phải có đúng 1 HS liên quan
    const relatedRows = page
      .getByTestId("related-item-table")
      .locator(".cssMaHSTLChild");
    await expect(relatedRows, {
      message:
        "Lỗi: Phiếu 1 không có hồ sơ liên quan — liên kết 2 chiều không được tạo",
    }).toHaveCount(1);

    const linkedCode = ((await relatedRows.first().textContent()) || "").trim();
    expect(linkedCode, {
      message: "Lỗi: Mã hồ sơ liên quan của phiếu 1 đang trống",
    }).not.toBe("");
  });
};

test(
  "UC29 1.1.2.9.81 - Kiểm tra HS/TL liên quan được lưu liên kết 2 chiều - Thủ thư" +
    ACCOUNT.LIBRARIAN,
  async ({ librarian }) => {
    await runTest(librarian);
  },
);
test(
  "UC29 1.1.2.9.81 - Kiểm tra HS/TL liên quan được lưu liên kết 2 chiều - Admin" +
    ACCOUNT.ADMIN,
  async ({ admin }) => {
    await runTest(admin);
  },
);
