// LP（外部ドメイン）の独自フォーム → /api/hooks/:token 直接POST の CORS 対応
import { describe, expect, it } from "vitest";
import { authed, login, setup } from "../helpers.js";

async function seedHook() {
  const s = setup();
  const cookie = await login(s.app);
  const list = (await (await s.app.request("/api/lists", authed(cookie, { name: "LP" }))).json()).list;
  const camp = (
    await (await s.app.request("/api/campaigns", authed(cookie, { name: "C", list_id: list.id }))).json()
  ).campaign;
  await s.app.request(`/api/campaigns/${camp.id}/steps`, authed(cookie, { subject: "S1", body_html: "b", timing_type: "immediate" }));
  const hook = (
    await (await s.app.request("/api/hooks", authed(cookie, { name: "LP", list_id: list.id, campaign_id: camp.id }))).json()
  ).hook;
  return { ...s, cookie, hook, camp };
}

describe("LP → hook 直接POST（CORS）", () => {
  it("OPTIONS プリフライトが 204 + CORSヘッダを返す", async () => {
    const { app, hook } = await seedHook();
    const res = await app.request(`/api/hooks/${hook.token}`, { method: "OPTIONS" });
    expect(res.status).toBe(204);
    expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
    expect(res.headers.get("Access-Control-Allow-Methods")).toContain("POST");
  });

  it("POST 成功時に CORSヘッダ付きで登録+ステップ開始する", async () => {
    const { app, store, hook, camp } = await seedHook();
    const res = await app.request(`/api/hooks/${hook.token}`, {
      method: "POST",
      headers: { "Content-Type": "application/json", Origin: "https://lp-harness.example" },
      body: JSON.stringify({ email: "reader@example.com", name: "読者" }),
    });
    expect(res.status).toBe(200);
    expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
    const j = await res.json();
    expect(j).toMatchObject({ ok: true, created: true, enrolled: true });
    expect((await store.listEnrollments(camp.id)).length).toBe(1);
  });

  it("不正メールは 400 でも CORSヘッダを返す（LP側でエラー表示可能）", async () => {
    const { app, hook } = await seedHook();
    const res = await app.request(`/api/hooks/${hook.token}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: "not-an-email" }),
    });
    expect(res.status).toBe(400);
    expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
  });
});
