import type { Actions, PageServerLoad } from './$types';
import { fail } from '@sveltejs/kit';
import { createAdmin, deleteAdmin, listAdmins } from '$lib/server/auth';

export const load: PageServerLoad = () => {
  return { admins: listAdmins() };
};

export const actions: Actions = {
  create: async ({ request }) => {
    const form = await request.formData();
    const username = String(form.get('username') ?? '');
    const password = String(form.get('password') ?? '');
    const confirm = String(form.get('confirm') ?? '');
    if (password !== confirm) {
      return fail(400, { error: 'Le password non coincidono.', username });
    }
    const result = createAdmin(username, password);
    if (!result.ok) return fail(400, { error: result.error, username });
    return { success: true, created: username.trim() };
  },

  delete: async ({ request, locals }) => {
    const form = await request.formData();
    const username = String(form.get('username') ?? '').trim();
    if (!username) return fail(400, { error: 'Username mancante.' });
    if (locals.admin?.username === username) {
      return fail(400, { error: 'Non puoi eliminare il tuo stesso account.' });
    }
    const result = deleteAdmin(username);
    if (!result.ok) return fail(400, { error: result.error });
    return { success: true, deleted: username };
  }
};
