<h1>Resource Usage</h1>

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

<div class="card">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
    <h2 style="font-size:15px;margin:0">Per-Firm Usage (latest daily rollup)</h2>
    <a href="/resource-usage/export.csv" class="btn" style="text-decoration:none">Export CSV</a>
  </div>
  <table>
    <thead><tr><th>Firm</th><th>Users</th><th>Active (30d)</th><th>Matters</th><th>Clients</th><th>Documents</th><th>Storage</th><th>Sessions (24h)</th><th>As Of</th></tr></thead>
    <tbody>
      <% for (const f of firms) { %>
      <tr>
        <td><%= f.firm_name %> <span style="color:var(--muted);font-size:11px">#<%= f.firm_id %></span></td>
        <td><%= f.total_users %></td>
        <td><%= f.active_users_30d %></td>
        <td><%= f.matter_count %></td>
        <td><%= f.client_count %></td>
        <td><%= f.document_count %></td>
        <td><%= (f.storage_bytes / (1024*1024)).toFixed(1) %> MB</td>
        <td><%= f.session_count_24h %></td>
        <td style="color:var(--muted);font-size:12px"><%= new Date(f.rollup_date).toLocaleDateString() %></td>
      </tr>
      <% } %>
      <% if (!firms.length) { %><tr><td colspan="9" style="color:var(--muted)">No usage data rolled up yet — the hourly rollup job needs at least one run.</td></tr><% } %>
    </tbody>
  </table>
</div>

<div class="card">
  <h2 style="font-size:15px;margin-top:0">Top Endpoints by Call Volume (last 7 days)</h2>
  <table>
    <thead><tr><th>Method</th><th>Endpoint</th><th>Calls</th></tr></thead>
    <tbody>
      <% for (const e of topEndpoints) { %>
      <tr>
        <td><code class="mono"><%= e.method %></code></td>
        <td><%= e.endpoint %></td>
        <td><%= e.totalCalls %></td>
      </tr>
      <% } %>
      <% if (!topEndpoints.length) { %><tr><td colspan="3" style="color:var(--muted)">No API call data rolled up yet.</td></tr><% } %>
    </tbody>
  </table>
</div>

<% } %>
