import type { AuditLog } from '@navi/types';
import { formatDate } from '@navi/ui';
import { AccessDenied } from '../../../components/AccessDenied';
import { EmptyState, PageHeader } from '../../../components/DashboardPrimitives';
import { dashboardApi } from '../../../lib/api';
import { requireDashboardRoute } from '../../../lib/permissions';

export default async function AuditLogs() {
  const gate = await requireDashboardRoute('/audit-logs');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;
  const logs = (await dashboardApi<AuditLog[]>('/audit-logs')) ?? [];

  return (
    <div className="stack">
      <PageHeader title="Audit logs" eyebrow="Security trail" />
      <div className="card">
        {logs.length ? (
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr><th>When</th><th>Actor</th><th>Action</th><th>Resource</th></tr>
              </thead>
              <tbody>
                {logs.map((log) => (
                  <tr key={log.id}>
                    <td>{formatDate(log.createdAt, 'en', { dateStyle: 'medium', timeStyle: 'short' })}</td>
                    <td className="mono">{log.actorId ?? log.actorType}</td>
                    <td>{log.action}</td>
                    <td>{log.resourceType}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <EmptyState title="No audit logs visible" body="Audited actions will appear after API mutations run under your readable audit scope." />
        )}
      </div>
    </div>
  );
}
