import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getDb } from "@/lib/db";
import { insertProject, listProjects, type ProjectPatch } from "@/lib/models";

export async function GET() {
  const list = listProjects(getDb(), "de");
  // wir geben eine flache Form zurück, die das Frontend für Listen/Edit braucht.
  return NextResponse.json({ projects: list.map(flatten) });
}

export async function POST(req: NextRequest) {
  let body: ProjectPatch;
  try {
    body = (await req.json()) as ProjectPatch;
  } catch {
    return NextResponse.json({ error: "bad_request" }, { status: 400 });
  }
  if (!body.slug || typeof body.slug !== "string") {
    return NextResponse.json({ error: "missing_slug" }, { status: 400 });
  }
  try {
    insertProject(getDb(), { ...body, slug: body.slug });
  } catch (e) {
    return NextResponse.json({ error: (e as Error).message }, { status: 400 });
  }
  return NextResponse.json({ ok: true });
}

type FlatProject = {
  slug: string;
  number: string;
  status: string;
  category: string;
  stack: string;
  href: string | null;
  featured: boolean;
  summaryDe: string;
  summaryEn: string;
  stanceDe: string;
  stanceEn: string;
  bodyDe: string;
  bodyEn: string;
  sortIndex: number;
};

function flatten(p: ReturnType<typeof listProjects>[number]): FlatProject {
  // Wir brauchen die zweisprachigen Inhalte für die Edit-Form, also lesen
  // wir sie hier noch einmal direkt aus der DB.
  const db = getDb();
  const row = db.prepare("SELECT * FROM projects WHERE slug = ?").get(p.slug) as {
    summary_de: string; summary_en: string; stance_de: string; stance_en: string;
    body_de: string; body_en: string;
  };
  return {
    slug: p.slug,
    number: p.number,
    status: p.status,
    category: p.category,
    stack: p.stack,
    href: p.href,
    featured: p.featured,
    summaryDe: row.summary_de,
    summaryEn: row.summary_en,
    stanceDe: row.stance_de,
    stanceEn: row.stance_en,
    bodyDe: row.body_de,
    bodyEn: row.body_en,
    sortIndex: p.sortIndex,
  };
}
