import { NextResponse } from "next/server";
import { listPinterestBoards } from "@/lib/pinterest-api";
import { addAudit, createId, readDb, writeDb } from "@/lib/store";
import { PinterestBoard } from "@/lib/types";

function normalizeName(value: string) {
  return value.trim().toLowerCase();
}

function normalizePrivacy(value: unknown): PinterestBoard["privacy"] {
  return value === "SECRET" || value === "PROTECTED" ? value : "PUBLIC";
}

export async function POST() {
  const result = await listPinterestBoards();
  if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status || 500 });

  const db = await readDb();
  const now = new Date().toISOString();
  let imported = 0;
  let updated = 0;

  for (const remoteBoard of result.data) {
    if (!remoteBoard.id || !remoteBoard.name) continue;

    const existing = db.boards.find((board) => board.apiBoardId === remoteBoard.id)
      || db.boards.find((board) => !board.apiBoardId && normalizeName(board.name) === normalizeName(remoteBoard.name));

    if (existing) {
      existing.apiBoardId = remoteBoard.id;
      existing.name = remoteBoard.name;
      existing.description = remoteBoard.description || existing.description || "";
      existing.privacy = normalizePrivacy(remoteBoard.privacy);
      existing.pinCount = remoteBoard.pin_count ?? existing.pinCount;
      existing.updatedAt = now;
      updated += 1;
      continue;
    }

    db.boards.unshift({
      id: createId("board"),
      apiBoardId: remoteBoard.id,
      name: remoteBoard.name,
      description: remoteBoard.description || "",
      privacy: normalizePrivacy(remoteBoard.privacy),
      pinCount: remoteBoard.pin_count,
      createdAt: remoteBoard.created_at || now,
      updatedAt: now,
    });
    imported += 1;
  }

  addAudit(db, {
    type: "content",
    actor: "api",
    title: "同步 Pinterest 图板",
    detail: `新增 ${imported} 个，更新 ${updated} 个。`,
    status: "completed",
  });
  await writeDb(db);

  return NextResponse.json({
    ok: true,
    imported,
    updated,
    remoteCount: result.data.length,
    boards: db.boards,
  });
}
