import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { getPostById, updatePost, deletePost } 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 }) => {
  const id = Number(params.id);
  if (!getPostById(getDb(), id)) return json(404, { error: 'Articolo non trovato.' });
  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 }) => {
  deletePost(getDb(), Number(params.id));
  return json(200, { ok: true });
};
