---
import Admin from '../../layouts/Admin.astro';
import { getDb } from '../../lib/db';
import { listAllPosts, listByAuthor } from '../../lib/posts';
import { listUsers } from '../../lib/auth';
export const prerender = false;
const user = Astro.locals.user!;
const isManager = user.role === 'superuser' || user.role === 'admin';
const posts = isManager ? listAllPosts(getDb()) : listByAuthor(getDb(), user.id);
const nameById = new Map(listUsers(getDb()).map((u) => [u.id, u.username]));
const fmt = new Intl.DateTimeFormat('it-IT', { dateStyle: 'short', timeStyle: 'short' });
---
<Admin title="Articoli">
  <h1>Articoli</h1>
  <p><a class="abtn" href="/admin/new">+ Nuovo articolo</a></p>
  <table>
    <thead><tr><th>Titolo</th><th>Categoria</th>{isManager && <th>Autore</th>}<th>Stato</th><th>Aggiornato</th><th></th></tr></thead>
    <tbody>
      {posts.map((p) => (
        <tr>
          <td><a href={`/admin/edit/${p.id}`}>{p.title}</a></td>
          <td>{p.category}</td>
          {isManager && <td>{p.author_id ? (nameById.get(p.author_id) ?? 'Staff InsanityLab') : 'Staff InsanityLab'}</td>}
          <td><span class:list={['pill', { 'pill--draft': p.draft }]}>{p.draft ? 'Bozza' : 'Pubblicato'}</span></td>
          <td>{fmt.format(new Date(p.updated_at.replace(' ', 'T') + 'Z'))}</td>
          <td><button class="abtn abtn--danger" data-del={p.id}>Elimina</button></td>
        </tr>
      ))}
    </tbody>
  </table>
  {posts.length === 0 && <p>Nessun articolo: creane uno nuovo.</p>}
</Admin>

<script>
  document.querySelectorAll<HTMLButtonElement>('[data-del]').forEach((b) =>
    b.addEventListener('click', async () => {
      if (!confirm('Eliminare definitivamente questo articolo?')) return;
      const res = await fetch(`/api/admin/posts/${b.dataset.del}`, { method: 'DELETE' });
      if (res.ok) location.reload();
      else alert('Eliminazione non riuscita.');
    }));
</script>
