import "dotenv/config";
import { describe, it, expect } from "vitest";
import type { Block, ProjectConfig } from "@/features/editor/state/editorStore";
import { buildStaticHtml } from "@/app/api/export/route";

const BASE_URL = "http://localhost";

// /api/export/preview TDD:
// - blocks + projectConfig 를 받아 HTML 문자열을 바로 반환하는 경량 엔드포인트.
// - 기존 buildStaticHtml 과 동일한 HTML 을 반환해야 한다.

describe("/api/export/preview", () => {
  it("POST /api/export/preview 는 blocks + projectConfig 로부터 HTML 문자열을 반환해야 한다", async () => {
    const blocks: Block[] = [
      {
        id: "blk_preview_text",
        type: "text",
        props: {
          text: "Export 미리보기 테스트",
          align: "center",
          size: "lg",
        },
      } as any,
    ];

    const projectConfig: ProjectConfig = {
      title: "Export 미리보기 페이지",
      slug: "export-preview",
      canvasPreset: "full",
    };

    const payload = { blocks, projectConfig };

    const { POST: handlePreview } = await import("@/app/api/export/preview/route");

    const res = await handlePreview(
      new Request(`${BASE_URL}/api/export/preview`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      }),
    );

    expect(res.status).toBe(200);
    expect(res.headers.get("Content-Type")).toBe("text/html; charset=utf-8");

    const html = await res.text();

    expect(html).toContain("<title>Export 미리보기 페이지</title>");
    expect(html).toContain("Export 미리보기 테스트");
  });

  it("/api/export/preview 의 HTML 은 동일 입력에 대해 buildStaticHtml 결과와 동일해야 한다", async () => {
    const blocks: Block[] = [
      {
        id: "blk_preview_compare",
        type: "text",
        props: {
          text: "Preview vs Export 동일성 테스트",
          align: "left",
          size: "base",
        },
      } as any,
    ];

    const projectConfig: ProjectConfig = {
      title: "동일성 테스트 페이지",
      slug: "preview-equality-test",
      canvasPreset: "full",
    };

    const payload = { blocks, projectConfig };

    const { POST: handlePreview } = await import("@/app/api/export/preview/route");

    const res = await handlePreview(
      new Request(`${BASE_URL}/api/export/preview`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      }),
    );

    const previewHtml = await res.text();
    const staticHtml = buildStaticHtml(blocks, projectConfig);

    expect(previewHtml).toBe(staticHtml);
  });
});
