---
import CrmLayout from '@/layouts/CrmLayout.astro';
import { listAuditLogs } from '@/lib/crm/store';
import { getUserById } from '@/lib/security/users';
import { formatDate } from '@/lib/util/format';

export const prerender = false;

function actionLabel(a: string): string {
  const map: Record<string, string> = {
    create: 'Creó',
    update: 'Editó',
    restore: 'Restauró',
    publish: 'Publicó',
    unpublish: 'Despublicó',
    stage_change: 'Cambió etapa',
    login: 'Inició sesión',
  };
  if (a === 'delete') return 'Eliminó';
  if (a === 'export') return 'Exportó';
  return map[a] ?? a;
}
function actionColor(a: string): string {
  if (a === 'create' || a === 'restore') return 'var(--pf-success)';
  if (a === 'delete') return '#ff7a8a';
  if (a === 'update') return 'var(--pf-accent-300)';
  if (a === 'stage_change') return 'var(--pf-warning)';
  return 'var(--pf-text)';
}

const rows = listAuditLogs()
  .slice(0, 200)
  .map((l) => {
    const u = l.actorUserId ? getUserById(l.actorUserId) : undefined;
    return {
      when: formatDate(l.createdAt),
      actor: u?.email ?? l.actorUserId ?? 'sistema',
      action: actionLabel(l.action),
      color: actionColor(l.action),
      entityType: l.entityType,
      entityId: l.entityId,
    };
  });
---

<CrmLayout title="Auditoría · CRM">
  <h1>Bitácora de auditoría</h1>
  <p class="muted">Últimos {rows.length} cambios. Toda mutación administrativa queda registrada (quién, qué, cuándo).</p>

  {rows.length === 0 && <p class="notice" style="margin-top:16px">Sin registros de auditoría aún.</p>}

  {
    rows.length > 0 && (
      <div class="table-wrap" style="margin-top:16px">
        <table class="data">
          <thead>
            <tr><th>Fecha</th><th>Usuario</th><th>Acción</th><th>Entidad</th><th>ID</th></tr>
          </thead>
          <tbody>
            {rows.map((r) => (
              <tr>
                <td style="white-space:nowrap">{r.when}</td>
                <td>{r.actor}</td>
                <td style={`font-weight:600;color:${r.color}`}>{r.action}</td>
                <td>{r.entityType}</td>
                <td style="font-family:monospace;font-size:.78rem">{r.entityId}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )
  }
</CrmLayout>
