import type { APIRoute } from 'astro';
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, cookies, locals }) => {
  const role = locals.user!.role;
  if (role !== 'superuser' && role !== 'admin') return json(403, { error: 'Permessi insufficienti' });
  let data: { on?: unknown };
  try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
  if (data.on) {
    cookies.set('showtags', '1', { httpOnly: true, sameSite: 'lax', path: '/', secure: import.meta.env.PROD });
  } else {
    cookies.delete('showtags', { path: '/' });
  }
  return json(200, { on: Boolean(data.on) });
};
