---
import Admin from '../../layouts/Admin.astro';
import { getDb } from '../../lib/db';
import { login, SESSION_COOKIE } from '../../lib/auth';
import { rateLimit } from '../../lib/rate-limit';
export const prerender = false;

let error = '';
if (Astro.request.method === 'POST') {
  if (!rateLimit(`login:${Astro.clientAddress}`, 5, 15 * 60 * 1000)) {
    error = 'Troppi tentativi: riprova tra 15 minuti.';
  } else {
    const form = await Astro.request.formData();
    const token = login(getDb(), String(form.get('username') ?? ''), String(form.get('password') ?? ''));
    if (token) {
      Astro.cookies.set(SESSION_COOKIE, token, {
        httpOnly: true, sameSite: 'lax', path: '/',
        secure: import.meta.env.PROD, maxAge: 7 * 24 * 3600,
      });
      return Astro.redirect('/admin');
    }
    error = 'Credenziali non valide.';
  }
}
---
<Admin title="Login">
  <h1>Accesso</h1>
  {error && <p style="color:#a33">{error}</p>}
  <form method="post" style="max-width:360px">
    <input class="afield" name="username" placeholder="Utente" required autocomplete="username" />
    <input class="afield" type="password" name="password" placeholder="Password" required autocomplete="current-password" />
    <button class="abtn" type="submit">Entra</button>
  </form>
</Admin>
