import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getDb } from "@/lib/db";
import { deleteProject, getProject, updateProject, type ProjectPatch } from "@/lib/models";

type FlatRow = {
  slug: string;
  number: string;
  status: string;
  category: string;
  stack: string;
  href: string | null;
  featured: number;
  summary_de: string;
  summary_en: string;
  stance_de: string;
  stance_en: string;
  body_de: string;
  body_en: string;
  sort_index: number;
};

function flatten(slug: string): Record<string, unknown> | null {
  const row = getDb().prepare("SELECT * FROM projects WHERE slug = ?").get(slug) as FlatRow | undefined;
  if (!row) return null;
  return {
    slug: row.slug,
    number: row.number,
    status: row.status,
    category: row.category,
    stack: row.stack,
    href: row.href,
    featured: row.featured === 1,
    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: row.sort_index,
  };
}

export async function GET(
  _req: NextRequest,
  ctx: { params: Promise<{ slug: string }> }
) {
  const { slug } = await ctx.params;
  const data = flatten(slug);
  if (!data) return NextResponse.json({ error: "not_found" }, { status: 404 });
  return NextResponse.json(data);
}

export async function PUT(
  req: NextRequest,
  ctx: { params: Promise<{ slug: string }> }
) {
  const { slug } = await ctx.params;
  let body: ProjectPatch;
  try {
    body = (await req.json()) as ProjectPatch;
  } catch {
    return NextResponse.json({ error: "bad_request" }, { status: 400 });
  }
  try {
    updateProject(getDb(), slug, body);
  } catch (e) {
    return NextResponse.json({ error: (e as Error).message }, { status: 400 });
  }
  return NextResponse.json({ ok: true });
}

export async function DELETE(
  _req: NextRequest,
  ctx: { params: Promise<{ slug: string }> }
) {
  const { slug } = await ctx.params;
  try {
    deleteProject(getDb(), slug);
  } catch (e) {
    return NextResponse.json({ error: (e as Error).message }, { status: 400 });
  }
  return NextResponse.json({ ok: true });
}
