import type { APIRoute } from 'astro';
import { getDb } from '../../../../lib/db';
import { createUser, listUsers, 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 GET: APIRoute = () => json(200, { users: listUsers(getDb()) });

export const POST: APIRoute = async ({ request }) => {
  let data: { username?: unknown; password?: unknown; role?: unknown };
  try { data = await request.json(); } catch { return json(400, { error: 'Dati non validi.' }); }
  const username = String(data.username ?? '').trim();
  const password = String(data.password ?? '');
  if (username.length < 2) return json(400, { error: 'Nome utente troppo corto.' });
  if (password.length < 8) return json(400, { error: 'Password troppo corta (min 8).' });
  if (!isRole(data.role)) return json(400, { error: 'Ruolo non valido.' });
  try {
    const id = createUser(getDb(), username, password, data.role);
    return json(201, { id });
  } catch (err: any) {
    if (String(err?.message).includes('UNIQUE')) return json(400, { error: 'Nome utente già esistente.' });
    throw err;
  }
};
