import { NextRequest, NextResponse } from "next/server";
import { addAudit, readDb, writeDb } from "@/lib/store";
import { exchangeCodeForToken } from "@/lib/pinterest-oauth";

export async function GET(req: NextRequest) {
  const code = req.nextUrl.searchParams.get("code") || "";
  const state = req.nextUrl.searchParams.get("state") || "";
  const error = req.nextUrl.searchParams.get("error") || "";

  if (error) {
    return NextResponse.json({ ok: false, error, errorDescription: req.nextUrl.searchParams.get("error_description") }, { status: 400 });
  }
  if (!code || !state) {
    return NextResponse.json({ ok: false, error: "code and state are required" }, { status: 400 });
  }

  const result = await exchangeCodeForToken({ code, state, origin: req.nextUrl.origin });
  if (!result.ok) return NextResponse.json(result, { status: 400 });

  const db = await readDb();
  addAudit(db, {
    type: "account",
    actor: "user",
    title: "Pinterest OAuth 已连接",
    detail: `scopes=${db.account.scopes.join(", ") || "n/a"}`,
    status: "completed",
  });
  await writeDb(db);

  return new NextResponse(
    `<!doctype html><html><head><meta charset="utf-8"><title>Pinterest connected</title></head><body style="font-family:Arial,sans-serif;padding:32px"><h1>Pinterest OAuth connected</h1><p>You can close this page and return to Pinterest-auto.</p><p><a href="/">Open dashboard</a></p></body></html>`,
    { headers: { "content-type": "text/html; charset=utf-8" } },
  );
}
