import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { createPost } from '../../../../lib/posts';
import { parsePostBody } from '../../../../lib/post-body';
export const prerender = false;

const json = (status: number, body: object) =>
  new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });

export const POST: APIRoute = async ({ request, locals }) => {
  let data: Record<string, unknown>;
  try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
  const parsed = parsePostBody(data);
  if ('error' in parsed) return json(400, { error: parsed.error });
  try {
    const id = createPost(getDb(), { ...parsed.value, author_id: locals.user!.id });
    return json(201, { id, slug: parsed.value.slug });
  } catch (err: any) {
    if (String(err?.message).includes('UNIQUE')) return json(400, { error: 'Slug già esistente.' });
    throw err;
  }
};
