import { resolve } from "node:path";

import { expect, test } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";

import { wp604AuditApiFixture, wp604PrivateAuditApiFixture } from "../fixtures/wp6-04-audit.js";

let vite: ViteDevServer;
let webUrl: string;

const adminSession = {
  acknowledged_private_content_notice_version: null,
  admin: { role: "super_admin", status: "active", user_id: "00000000-0000-4000-8000-000000000604" },
  audience: "admin",
  authenticated: true,
  csrf_token: "csrf-wp6-04-admin-0000000000000000000000000000000000",
  current_private_content_notice_version: null,
  expires_at: "2026-09-04T09:30:00.000Z",
  notice_acknowledged: false,
};

test.beforeAll(async () => {
  vite = await createServer({ configFile: resolve("apps/web/vite.config.ts"), root: resolve("apps/web"), server: { host: "127.0.0.1", port: 0 } });
  await vite.listen();
  const address = vite.httpServer?.address();
  if (!address || typeof address === "string") throw new Error("Vite did not expose a test port.");
  webUrl = `http://127.0.0.1:${address.port}`;
});

test.afterAll(async () => vite.close());

test("TDD-WP6-AUD-001-sensitive-operations renders two immutable, redacted audit lists", async ({ page }) => {
  await page.route("**/api/v1/admin-auth/session", (route) => route.fulfill({ body: JSON.stringify(adminSession), contentType: "application/json", status: 200 }));
  await page.route("**/api/v1/admin/audit/operations**", (route) => route.fulfill({ body: JSON.stringify(wp604AuditApiFixture), contentType: "application/json", status: 200 }));
  await page.route("**/api/v1/admin/audit/private-content**", (route) => route.fulfill({ body: JSON.stringify(wp604PrivateAuditApiFixture), contentType: "application/json", status: 200 }));

  await page.goto(`${webUrl}/admin/audit`);
  await expect(page.getByRole("heading", { level: 2, name: "审计" })).toBeVisible();
  await expect(page.getByRole("tab", { name: "后台操作审计" })).toHaveAttribute("aria-selected", "true");
  await expect(page.getByRole("cell", { name: "user_status_change" })).toBeVisible();
  await expect(page.getByRole("button", { name: "下一页" })).toBeVisible();

  await page.getByRole("tab", { name: "私有内容访问审计" }).click();
  await expect(page.getByRole("cell", { name: "prompt" })).toBeVisible();
  await expect(page.getByRole("cell", { name: "00000000-0000-4000-8000-000000000644" })).toBeVisible();
  await expect(page.getByText(/private prompt body|api key|absolute path/i)).toHaveCount(0);
  await expect(page.getByRole("button", { name: /删除|编辑|清空/ })).toHaveCount(0);

  const evidenceRoot = process.env.DADA_EVIDENCE_DIR_WP6_AUD;
  if (evidenceRoot) await page.screenshot({ fullPage: true, path: resolve(evidenceRoot, "admin-audit.png") });
});
