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

export default async function ProviderAuditHistory() {
  const gate = await requireDashboardRoute('/provider-audit-history');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;

  const logs = (await dashboardApi<ProviderControlAuditDto[]>('/provider-control/audit-history?limit=100')) ?? [];

  return (
    <div className="stack">
      <PageHeader title="Provider audit history" eyebrow="Control Tower" />
      <Notice tone="info" title="Read-only timeline" body="Every category mode change, integration create/update/disable, and health check is read from AuditLog. This page does not edit operational state." />
      <div className="card">
        {logs.length ? (
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Action</th><th>Resource</th><th>Actor</th><th>When</th><th>Before</th><th>After</th></tr></thead>
              <tbody>
                {logs.map((log) => (
                  <tr key={log.id}>
                    <td><StatusBadge value={log.action} /></td>
                    <td>
                      <strong>{log.resourceType}</strong>
                      <div className="muted mono">{log.resourceId ?? 'n/a'}</div>
                    </td>
                    <td>{log.actorId ?? log.actorType}</td>
                    <td>{formatDate(log.createdAt)}</td>
                    <td className="mono">{compactAudit(log.before)}</td>
                    <td className="mono">{compactAudit(log.after)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <EmptyState title="No provider control audit entries" body="Category mode changes, integration edits, disables, and health checks will appear here." />
        )}
      </div>
    </div>
  );
}

function compactAudit(value: unknown): string {
  if (!value) return 'n/a';
  const text = JSON.stringify(value);
  return text.length > 180 ? `${text.slice(0, 180)}...` : text;
}
