import { expect, test } from "@playwright/test";

test("案例库列表和人味文案详情可查看", async ({ page }) => {
  await mockAuthenticatedSession(page, true);
  await page.route("**/api/cases", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        cases: [
          {
            id: "case_copy_1",
            case_type: "human_copy",
            title: "人味文案优化：朋友圈",
            summary: "原始文案摘要",
            status: "optimized",
            customer_name: "客户A",
            brand_name: "品牌B",
            project_tags: ["朋友圈"],
            notes: "",
            publish_target: "朋友圈",
            source_excerpt: "原始文案摘要",
            result_excerpt: "优化后文案摘要",
            latest_result_version_id: "ver_copy_1",
            latest_version_number: 1,
            last_error_stage: null,
            last_error_summary: null,
            archived_at: null,
            created_at: "2026-07-08T10:00:00.000Z",
            updated_at: "2026-07-08T10:05:00.000Z",
          },
        ],
      }),
    });
  });
  await page.route("**/api/cases/case_copy_1", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        case: {
          id: "case_copy_1",
          case_type: "human_copy",
          title: "人味文案优化：朋友圈",
          summary: "原始文案摘要",
          status: "optimized",
          customer_name: "客户A",
          brand_name: "品牌B",
          project_tags: ["朋友圈"],
          notes: "",
          publish_target: "朋友圈",
          source_excerpt: "原始文案摘要",
          result_excerpt: "优化后文案摘要",
          latest_result_version_id: "ver_copy_1",
          latest_version_number: 1,
          last_error_stage: null,
          last_error_summary: null,
          archived_at: null,
          created_at: "2026-07-08T10:00:00.000Z",
          updated_at: "2026-07-08T10:05:00.000Z",
        },
        input: {
          case_id: "case_copy_1",
          case_type: "human_copy",
          article_job_id: null,
          payload: {
            source_text: "原始文案",
            goal: "自然一点",
            intensity: "light",
            user_instructions: "",
            publish_target: "朋友圈",
          },
          created_at: "2026-07-08T10:00:00.000Z",
          updated_at: "2026-07-08T10:00:00.000Z",
        },
        versions: [
          {
            id: "ver_copy_1",
            case_id: "case_copy_1",
            case_type: "human_copy",
            version: 1,
            status: "optimized",
            article_job_id: null,
            article_revision: null,
            result_summary: "优化后文案摘要",
            payload: {
              optimized_text: "优化后文案",
              change_notes: [
                {
                  original: "原始文案",
                  revised: "优化后文案",
                  reason: "减少书面腔。",
                  confidence: "confident",
                  revertible: false,
                },
              ],
              ai_taste_checks: [
                {
                  rule_id: "promotion_tone",
                  status: "pass",
                  evidence: "没有新增宣传腔。",
                  suggestion: "",
                },
              ],
              warnings: [],
            },
            process_summary: [],
            llm_audit_summary: [],
            error_stage: null,
            error_summary: null,
            created_at: "2026-07-08T10:05:00.000Z",
          },
        ],
      }),
    });
  });
  await page.route(
    "**/api/cases/case_copy_1/versions/ver_copy_1/publications",
    async (route) => {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ publications: [] }),
      });
    },
  );

  await page.goto("/cases");
  await expect(page.getByRole("heading", { name: "案例库" })).toBeVisible();
  await expect(page.getByText("人味文案优化：朋友圈")).toBeVisible();
  await page.getByRole("link", { name: "人味文案优化：朋友圈" }).click();
  await expect(
    page.locator(".copy-result").filter({ hasText: "优化后文案" }),
  ).toBeVisible();
  await expect(page.getByText("AI 味检查")).toBeVisible();
  await expect(page.getByText("发布表现")).toBeVisible();
});

test("案例库可以通过访问密钥建立浏览器登录态", async ({ page }) => {
  let authenticated = false;
  await page.route("**/api/auth/session", async (route) => {
    const request = route.request();
    if (request.method() === "GET") {
      await route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({ authenticated }),
      });
      return;
    }
    if (request.method() === "POST") {
      const payload = request.postDataJSON() as { api_access_key?: string };
      authenticated = payload.api_access_key === "local-dev-key";
      await route.fulfill({
        status: authenticated ? 200 : 401,
        contentType: "application/json",
        body: JSON.stringify(
          authenticated
            ? { authenticated: true }
            : { error: "Unauthorized" },
        ),
      });
      return;
    }
    await route.fulfill({ status: 405 });
  });
  await page.route("**/api/cases", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        cases: [
          {
            id: "case_article_1",
            case_type: "article",
            title: "伟思德鲁官网文章优化案例",
            summary: "优化后摘要",
            status: "optimized",
            customer_name: "",
            brand_name: "",
            project_tags: [],
            notes: "",
            publish_target: "official_site",
            source_excerpt: "原文摘要",
            result_excerpt: "优化后摘要",
            latest_result_version_id: "ver_article_1",
            latest_version_number: 1,
            last_error_stage: null,
            last_error_summary: null,
            archived_at: null,
            created_at: "2026-07-08T10:00:00.000Z",
            updated_at: "2026-07-08T10:05:00.000Z",
          },
        ],
      }),
    });
  });

  await page.goto("/cases");
  await expect(page.getByText("请先登录后查看案例库。")).toBeVisible();
  await page.getByLabel("访问密钥").fill("local-dev-key");
  await page.getByRole("button", { name: "确认登录" }).click();
  await expect(page.getByText("已登录")).toBeVisible();
  await expect(page.getByText("伟思德鲁官网文章优化案例")).toBeVisible();
});

async function mockAuthenticatedSession(
  page: Parameters<Parameters<typeof test>[1]>[0]["page"],
  authenticated: boolean,
) {
  await page.route("**/api/auth/session", async (route) => {
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({ authenticated }),
    });
  });
}
