import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { getPostById, updatePost, deletePost, canModifyPost } 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 PUT: APIRoute = async ({ params, request, locals }) => {
  const id = Number(params.id);
  const existing = getPostById(getDb(), id);
  if (!existing) return json(404, { error: 'Articolo non trovato.' });
  if (!canModifyPost(locals.user!.role, locals.user!.id, existing)) return json(403, { error: 'Non puoi modificare questo articolo.' });
  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 {
    updatePost(getDb(), id, parsed.value);
    return json(200, { ok: true });
  } catch (err: any) {
    if (String(err?.message).includes('UNIQUE')) return json(400, { error: 'Slug già esistente.' });
    throw err;
  }
};

export const DELETE: APIRoute = ({ params, locals }) => {
  const id = Number(params.id);
  const existing = getPostById(getDb(), id);
  if (!existing) return json(404, { error: 'Articolo non trovato.' });
  if (!canModifyPost(locals.user!.role, locals.user!.id, existing)) return json(403, { error: 'Non puoi eliminare questo articolo.' });
  deletePost(getDb(), id);
  return json(200, { ok: true });
};
