import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { importCsvRows } from "@/lib/content/csv-import";
import { attachManualContentQa } from "@/lib/content/manual-content-qa";
import { getUserProjects } from "@/lib/storage/projects";
import { saveGeneratedPost } from "@/lib/storage/generated-posts";

export async function POST(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const formData = await request.formData();
  const file = formData.get("file");
  const projectId = String(formData.get("projectId") ?? "").trim();

  if (!projectId) {
    return NextResponse.json({ error: "projectId is required" }, { status: 400 });
  }
  if (!(file instanceof File)) {
    return NextResponse.json({ error: "CSV file is required" }, { status: 400 });
  }

  const snapshot = await getUserProjects(user.id);
  const project = snapshot?.projects.find((p) => p.id === projectId);
  if (!project) {
    return NextResponse.json({ error: "Project not found" }, { status: 404 });
  }

  const data = snapshot?.dataByProjectId?.[projectId];
  if (!data) {
    return NextResponse.json({ error: "Project data not found" }, { status: 404 });
  }

  const csvText = await file.text();

  try {
    const result = importCsvRows(csvText, user.id, project, data.brand, data.context);
    for (const post of result.posts) {
      const withQa = attachManualContentQa(post, data.brand, data.context);
      await saveGeneratedPost(withQa);
    }
    return NextResponse.json({
      success: true,
      imported: result.imported,
      errors: result.errors,
      postIds: result.posts.map((p) => p.id),
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "CSV import failed";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
