import type { Actions } from './$types';
import { fail, redirect } from '@sveltejs/kit';
import { createSession, verifyCredentials } from '$lib/server/auth';

export const actions: Actions = {
  default: async ({ request, cookies }) => {
    const form = await request.formData();
    const username = String(form.get('username') ?? '').trim();
    const password = String(form.get('password') ?? '');
    if (!username || !password) {
      return fail(400, { error: 'Compila username e password.', username });
    }
    if (!verifyCredentials(username, password)) {
      return fail(401, { error: 'Credenziali non valide.', username });
    }
    createSession(username, cookies);
    throw redirect(303, '/admin');
  }
};
