<h1>API Keys</h1>

<% if (forbidden) { %>
  <div class="alert alert-danger">Your role does not have permission to manage API keys.</div>
<% } else { %>

<% if (error) { %><div class="alert alert-danger"><%= error %></div><% } %>
<% if (issuedKey) { %>
  <div class="alert alert-ok">
    <strong>API key issued — copy it now, it will not be shown again:</strong><br>
    <code class="mono" style="font-size:13px"><%= issuedKey %></code>
  </div>
<% } %>

<div class="card">
  <p style="color:var(--muted);font-size:12px">Gates <code class="mono">GET /api/v1/external/matters/summary</code> (a real, working demo endpoint — send the key as an <code class="mono">X-API-Key</code> header) — see docs/ADMIN_CONSOLE.md.</p>
  <table>
    <thead><tr><th>Firm</th><th>Name</th><th>Prefix</th><th>Rate Limit</th><th>Status</th><th>Last Used</th><th></th></tr></thead>
    <tbody>
      <% for (const k of keys) { %>
      <tr>
        <td>#<%= k.firm_id %> <%= k.firm_name %></td>
        <td><%= k.name %></td>
        <td><code class="mono"><%= k.key_prefix %>…</code></td>
        <td><%= k.rate_limit_per_minute %>/min</td>
        <td><span class="badge <%= k.is_active ? 'badge-ok' : 'badge-danger' %>"><%= k.is_active ? 'Active' : 'Revoked' %></span></td>
        <td><%= k.last_used_at ? new Date(k.last_used_at).toLocaleString() : 'Never' %></td>
        <td><% if (k.is_active) { %><form method="post" action="/ops/api-keys/<%= k.id %>/revoke"><button class="link-btn" type="submit">Revoke</button></form><% } %></td>
      </tr>
      <% } %>
      <% if (!keys.length) { %><tr><td colspan="7" style="color:var(--muted)">No API keys issued.</td></tr><% } %>
    </tbody>
  </table>
</div>

<div class="card" style="max-width:420px">
  <h2 style="font-size:15px;margin-top:0">Issue New Key</h2>
  <p style="color:var(--muted);font-size:12px">Requires a fresh re-auth.</p>
  <form method="post" action="/ops/api-keys">
    <label>Firm</label>
    <div data-firm-search style="position:relative">
      <input type="text" data-firm-search-input placeholder="Search firms by name or email…" autocomplete="off" required>
      <input type="hidden" name="firmId" data-firm-search-hidden>
      <ul data-firm-search-results class="firm-search-results" hidden></ul>
    </div>
    <label>Key Name</label>
    <input type="text" name="name" required placeholder="e.g. Firm's internal reporting tool">
    <label>Rate Limit (requests/min)</label>
    <input type="number" name="rateLimitPerMinute" value="60">
    <button class="btn" type="submit" style="width:100%;margin-top:16px">Issue Key</button>
  </form>
</div>

<% } %>
