import { test as base, Page } from "@playwright/test";
import { promises as fs } from "fs";
import { createAuthContext } from "../utils/auth-helper";
import { loadAccounts } from "../utils/account-loader";

const accounts = loadAccounts();

export const ACCOUNT = {
  LIBRARIAN: "ecm01",
  ADMIN: "ecm09",
  END_USER: "ecm04",
};
// 1. Khai báo danh sách 9 Nhân vật (Để gõ code nó tự gợi ý - Auto complete)
type AppRoles = {
  ecm01: Page;
  ecm02: Page;
  ecm03: Page;
  ecm04: Page;
  ecm05: Page;
  ecm06: Page;
  ecm07: Page;
  ecm08: Page;
  ecm09: Page;
  admin: Page;
  librarian: Page;
  end_user: Page;
};

const QA_REVIEW_MODE = process.env.QA_REVIEW_MODE === "true";

// 2. Viết 1 HÀM MẪU đóng gói toàn bộ logic phức tạp (Context, Video, Trace...)
const buildRole = (accountId: string) => {
  return async ({ browser }: any, use: any, testInfo: any) => {
    const account = accounts.find((acc) => acc.id === accountId);
    if (!account) {
      throw new Error(`Không tìm thấy account ${accountId}`);
    }
    // SETUP
    const context = await createAuthContext(browser, account, {
      recordVideo: { dir: "test-results/videos/" },
    });
    const page = await context.newPage();

    // YIELD
    await use(page);

    // TEARDOWN
    const video = page.video();

    if (video) {
      const videoPath = await video.path();
      const isFailed = testInfo.status !== testInfo.expectedStatus;
      if (isFailed || QA_REVIEW_MODE) {
        // Test thất bại hoặc đang QA Review Mode — đính kèm video vào report
        await testInfo.attach(`Video - ${accountId}`, {
          path: videoPath,
          contentType: "video/webm",
        });
      } else {
        // Test thành công và không ở QA Review Mode — xóa video để tiết kiệm dung lượng
        await fs.unlink(videoPath).catch(() => {});
      }
    }
    await context.close();
  };
};

// 3. ĐĂNG KÝ 9 NHÂN VẬT (Code giờ đây siêu ngắn và sạch)
export const test = base.extend<AppRoles>({
  ecm01: buildRole("ecm01"),
  ecm02: buildRole("ecm02"),
  ecm03: buildRole("ecm03"),
  ecm04: buildRole("ecm04"),
  ecm05: buildRole("ecm05"),
  ecm06: buildRole("ecm06"),
  ecm07: buildRole("ecm07"),
  ecm08: buildRole("ecm08"),
  ecm09: buildRole("ecm09"),
  admin: buildRole(ACCOUNT.ADMIN),
  librarian: buildRole(ACCOUNT.LIBRARIAN),
  end_user: buildRole(ACCOUNT.END_USER),
});

export { expect } from "@playwright/test";
