import { NextRequest, NextResponse } from "next/server";
import { checkCommercialGateWithHeartbeat } from "@/lib/commercial";
import { addAudit, createId, readDb, writeDb } from "@/lib/store";
import { PinterestTrendResearch } from "@/lib/types";

export async function GET() {
  const db = await readDb();
  return NextResponse.json({ trendResearch: db.trendResearch });
}

export async function POST(req: NextRequest) {
  const body = await req.json().catch(() => ({}));
  const seedKeyword = String(body.seedKeyword || body.keyword || "").trim();
  if (!seedKeyword) return NextResponse.json({ error: "seedKeyword required" }, { status: 400 });

  const now = new Date().toISOString();
  const market = String(body.market || "US");
  const terms = buildLocalTrendTerms(seedKeyword);
  const research: PinterestTrendResearch = {
    id: createId("trend"),
    seedKeyword,
    market,
    terms,
    summary: `已围绕「${seedKeyword}」生成 ${terms.length} 个趋势/内容方向。接入 Pinterest Trends API 后可替换为真实热度数据。`,
    createdAt: now,
  };
  const db = await readDb();
  const gate = await checkCommercialGateWithHeartbeat(db, "trend_research");
  if (!gate.ok) {
    await writeDb(db);
    return NextResponse.json({ ok: false, error: gate.error, snapshot: gate.snapshot }, { status: gate.status });
  }
  db.trendResearch.unshift(research);
  addAudit(db, {
    type: "trend",
    actor: "user",
    title: "创建趋势研究",
    detail: `${seedKeyword} / ${market}`,
    status: "completed",
  });
  await writeDb(db);
  return NextResponse.json({ research });
}

function buildLocalTrendTerms(seed: string): PinterestTrendResearch["terms"] {
  return [
    { keyword: `${seed} ideas`, category: "content", intent: "idea", score: 82, reason: "Pinterest 用户常以 ideas 寻找可执行灵感。" },
    { keyword: `${seed} aesthetic`, category: "style", intent: "seasonal", score: 74, reason: "适合扩展视觉风格、图板命名和素材方向。" },
    { keyword: `${seed} diy`, category: "how-to", intent: "idea", score: 68, reason: "教程型 Pin 通常更容易保存。" },
    { keyword: `${seed} shopping`, category: "commerce", intent: "shopping", score: 66, reason: "适合承接商品 Pin、目录和落地页。" },
    { keyword: `${seed} gift`, category: "seasonal", intent: "seasonal", score: 61, reason: "可用于节日和送礼场景内容日历。" },
  ];
}
