import type { APIRoute } from 'astro';
import { getDb } from '../../../../../lib/db';
import { getUserById, updateUserRole, countAdmins, isRole } from '../../../../../lib/auth';
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);
  const target = getUserById(getDb(), id);
  if (!target) return json(404, { error: 'Utente inesistente.' });
  let data: { role?: unknown };
  try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
  if (!isRole(data.role)) return json(400, { error: 'Ruolo non valido.' });
  if (target.role === 'admin' && data.role !== 'admin' && countAdmins(getDb()) <= 1) {
    return json(400, { error: 'Deve restare almeno un admin.' });
  }
  updateUserRole(getDb(), id, data.role);
  return json(200, { ok: true });
};
