import type { APIRoute } from 'astro';
import { getDb } from '../../../../../lib/db';
import { getUserById, updateUserPassword, hashPassword, randomPassword } 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 POST: APIRoute = ({ params }) => {
  const id = Number(params.id);
  if (!getUserById(getDb(), id)) return json(404, { error: 'Utente inesistente.' });
  const password = randomPassword();
  updateUserPassword(getDb(), id, hashPassword(password));
  // La password in chiaro è restituita UNA sola volta: l'admin la copia e la consegna.
  return json(200, { password });
};
