{% extends 'layout.twig' %}

{% block title %}Audit — IRDB{% endblock %}

{% macro action_pill(action) %}
    {%- set bucket = action|split('.')[0]|default('') -%}
    {%- set classes = {
        'reporter':       'bg-blue-100 text-blue-900 dark:bg-blue-900 dark:text-blue-100',
        'consumer':       'bg-cyan-100 text-cyan-900 dark:bg-cyan-900 dark:text-cyan-100',
        'token':          'bg-purple-100 text-purple-900 dark:bg-purple-900 dark:text-purple-100',
        'policy':         'bg-indigo-100 text-indigo-900 dark:bg-indigo-900 dark:text-indigo-100',
        'category':       'bg-violet-100 text-violet-900 dark:bg-violet-900 dark:text-violet-100',
        'manual_block':   'bg-amber-100 text-amber-900 dark:bg-amber-900 dark:text-amber-100',
        'allowlist':      'bg-emerald-100 text-emerald-900 dark:bg-emerald-900 dark:text-emerald-100',
        'job':            'bg-slate-200 text-slate-800 dark:bg-slate-700 dark:text-slate-100',
    } -%}
    <span class="inline-block rounded px-2 py-0.5 font-mono text-[0.7rem] uppercase tracking-tight {{ classes[bucket]|default('bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300') }}">{{ action }}</span>
{% endmacro %}

{% block content %}
{% import _self as h %}
{% import 'partials/sort.twig' as sort %}
<div class="mx-auto max-w-6xl">
    <div class="flex items-center justify-between">
        <h1 class="text-2xl font-semibold tracking-tight">Audit log</h1>
        {% if list %}
            <span class="text-sm text-slate-500 dark:text-slate-400">{{ list.total }} total</span>
        {% endif %}
    </div>

    {% if error %}
        <div class="mt-4 rounded-md border border-red-300 bg-red-50 px-4 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-300">{{ error }}</div>
    {% endif %}

    {% if filters.subject_kind and filters.subject_id %}
        <div class="mt-4 flex items-center justify-between rounded-md border border-indigo-200 bg-indigo-50 px-4 py-2 text-sm text-indigo-900 dark:border-indigo-800 dark:bg-indigo-950 dark:text-indigo-200">
            <span>
                Filtering events for {{ filters.subject_kind }} <span class="font-mono">#{{ filters.subject_id }}</span>
                — both events <em>about</em> it and events emitted <em>by</em> it.
            </span>
            <a href="/app/audit" class="text-xs font-medium underline">clear</a>
        </div>
    {% endif %}

    <form id="audit-filter-form" method="get" action="/app/audit" class="mt-4 grid grid-cols-2 gap-3 rounded-2xl border border-slate-200 bg-white p-4 text-sm shadow-sm dark:border-slate-800 dark:bg-slate-900 md:grid-cols-7">
        {# Subject filter is set by per-entity links (reporter/consumer detail) and
           preserved across re-submits of this form so a manual filter change
           doesn't silently widen the result. Form has no UI control for it. #}
        {% if filters.subject_kind %}<input type="hidden" name="subject_kind" value="{{ filters.subject_kind }}">{% endif %}
        {% if filters.subject_id %}<input type="hidden" name="subject_id" value="{{ filters.subject_id }}">{% endif %}
        <div>
            <label for="f-actor-kind" class="block text-xs font-medium text-slate-600 dark:text-slate-400">Actor kind</label>
            <select id="f-actor-kind" name="actor_kind" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
                <option value="">— any —</option>
                {% for k in allowed_kinds %}
                    <option value="{{ k }}" {% if filters.actor_kind == k %}selected{% endif %}>{{ k }}</option>
                {% endfor %}
            </select>
        </div>
        <div>
            <label for="f-actor-id" class="block text-xs font-medium text-slate-600 dark:text-slate-400">Actor id</label>
            <input type="number" id="f-actor-id" name="actor_id" min="1" value="{{ filters.actor_id|default('') }}"
                   class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
        </div>
        <div class="col-span-2">
            <label for="f-action" class="block text-xs font-medium text-slate-600 dark:text-slate-400">Action</label>
            <select id="f-action" name="action" class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
                <option value="">— any —</option>
                {% for a in allowed_actions %}
                    <option value="{{ a }}" {% if filters.action == a %}selected{% endif %}>{{ a }}</option>
                {% endfor %}
            </select>
        </div>
        <div>
            <label for="f-entity-type" class="block text-xs font-medium text-slate-600 dark:text-slate-400">Entity type</label>
            <input type="text" id="f-entity-type" name="entity_type" value="{{ filters.entity_type|default('') }}"
                   class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
        </div>
        <div>
            <label for="f-entity-id" class="block text-xs font-medium text-slate-600 dark:text-slate-400">Entity id</label>
            <input type="text" id="f-entity-id" name="entity_id" value="{{ filters.entity_id|default('') }}"
                   class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
        </div>
        <div class="col-span-2 md:col-span-7 grid grid-cols-1 gap-3 md:grid-cols-3 md:items-end">
            <div>
                <label for="f-from" class="block text-xs font-medium text-slate-600 dark:text-slate-400">From</label>
                <input type="datetime-local" id="f-from" name="from" step="1" data-irdb-iso-filter="{{ filters.from|default('') }}"
                       class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
            </div>
            <div>
                <label for="f-to" class="block text-xs font-medium text-slate-600 dark:text-slate-400">To</label>
                <input type="datetime-local" id="f-to" name="to" step="1" data-irdb-iso-filter="{{ filters.to|default('') }}"
                       class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-sm dark:border-slate-700 dark:bg-slate-950">
            </div>
            <div class="flex justify-end gap-2">
                <a href="/app/audit" class="rounded-md border border-slate-300 px-3 py-1.5 text-sm hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">Reset</a>
                <button type="submit" class="rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-indigo-500">Filter</button>
            </div>
        </div>
    </form>

    {# Datetime-local ⇄ ISO round-tripping for the filter form lives in
       app.js (initAuditFilterForm) so this page has no inline JS. #}

    {% if list %}
        <div class="mt-6 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900" x-data="rowExpander">
            <table class="w-full text-sm" data-sortable-table="audit-index">
                <thead class="border-b border-slate-200 bg-slate-50 text-left text-xs uppercase tracking-wider text-slate-500 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-400">
                    <tr>
                        {{ sort.th('When', 'when', 'date') }}
                        {{ sort.th('Actor', 'actor') }}
                        {{ sort.th('Action', 'action') }}
                        {{ sort.th('Entity', 'entity') }}
                        {{ sort.th('Source IP', 'source_ip') }}
                        <th class="px-4 py-2 font-medium text-right">Payload</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100 dark:divide-slate-800">
                    {% for ev in list.items %}
                        <tr>
                            <td class="px-4 py-2 align-top" data-sort-value="{{ ev.occurred_at }}"><time class="irdb-dt font-mono text-xs text-slate-600 dark:text-slate-300" datetime="{{ ev.occurred_at }}" title="{{ ev.occurred_at }}">{{ ev.occurred_at }}</time></td>
                            <td class="px-4 py-2 align-top text-xs" data-sort-value="{{ ev.actor_kind }} {{ ev.actor_id|default('') }}">
                                <span class="rounded bg-slate-100 px-1.5 py-0.5 font-mono uppercase tracking-tight text-slate-700 dark:bg-slate-800 dark:text-slate-300">{{ ev.actor_kind }}</span>
                                {% if ev.actor_id %}<span class="ml-1 font-mono text-slate-500">#{{ ev.actor_id }}</span>{% endif %}
                            </td>
                            <td class="px-4 py-2 align-top" data-sort-value="{{ ev.action }}">{{ h.action_pill(ev.action) }}</td>
                            <td class="px-4 py-2 align-top text-xs" data-sort-value="{{ ev.entity_type|default('') }} {{ ev.entity_label|default('') }} {{ ev.entity_id|default('') }}">
                                <span class="font-mono text-slate-600 dark:text-slate-300">{{ ev.entity_type|default('—') }}</span>
                                {% if ev.entity_label %}
                                    <span class="ml-1 font-medium text-slate-800 dark:text-slate-100">{{ ev.entity_label }}</span>
                                    {% if ev.entity_id %}<span class="ml-1 font-mono text-[0.7rem] text-slate-400">#{{ ev.entity_id }}</span>{% endif %}
                                {% elseif ev.entity_id %}
                                    <span class="ml-1 font-mono text-slate-500">#{{ ev.entity_id }}</span>
                                {% endif %}
                            </td>
                            <td class="px-4 py-2 align-top font-mono text-xs text-slate-500" data-sort-value="{{ ev.source_ip|default('') }}">{{ ev.source_ip|default('—') }}</td>
                            <td class="px-4 py-2 align-top text-right">
                                {% if ev.details %}
                                    <button type="button" x-on:click="toggle({{ ev.id }})" class="rounded border border-slate-300 px-2 py-0.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">View</button>
                                {% else %}
                                    <span class="text-xs text-slate-400">—</span>
                                {% endif %}
                            </td>
                        </tr>
                        {% if ev.details %}
                            <tr x-show="isOpen({{ ev.id }})" x-cloak data-sort-row-detail>
                                <td colspan="6" class="bg-slate-50 px-4 py-3 dark:bg-slate-950">
                                    {% if ev.details.changes is defined and ev.details.changes is iterable and ev.details.changes|length > 0 %}
                                        <div class="mb-3">
                                            <div class="mb-1 text-[0.7rem] font-semibold uppercase tracking-wider text-slate-500 dark:text-slate-400">Changes</div>
                                            <table class="w-full text-xs">
                                                <thead class="text-left text-[0.7rem] uppercase text-slate-500 dark:text-slate-400">
                                                    <tr>
                                                        <th class="px-2 py-1 font-medium">Field</th>
                                                        <th class="px-2 py-1 font-medium">Before</th>
                                                        <th class="px-2 py-1 font-medium">After</th>
                                                    </tr>
                                                </thead>
                                                <tbody class="divide-y divide-slate-200 bg-white dark:divide-slate-800 dark:bg-slate-900">
                                                    {% for field, change in ev.details.changes %}
                                                        <tr>
                                                            <td class="px-2 py-1 font-mono text-slate-700 dark:text-slate-200">{{ field }}</td>
                                                            <td class="px-2 py-1 align-top">
                                                                {% if change.from is null %}
                                                                    <span class="text-slate-400">∅</span>
                                                                {% elseif change.from is iterable %}
                                                                    <pre class="overflow-x-auto rounded bg-rose-50 px-2 py-1 font-mono text-[0.7rem] text-rose-900 dark:bg-rose-950 dark:text-rose-200">{{ change.from|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
                                                                {% else %}
                                                                    <span class="rounded bg-rose-50 px-1.5 py-0.5 font-mono text-rose-900 dark:bg-rose-950 dark:text-rose-200">{{ change.from }}</span>
                                                                {% endif %}
                                                            </td>
                                                            <td class="px-2 py-1 align-top">
                                                                {% if change.to is null %}
                                                                    <span class="text-slate-400">∅</span>
                                                                {% elseif change.to is iterable %}
                                                                    <pre class="overflow-x-auto rounded bg-emerald-50 px-2 py-1 font-mono text-[0.7rem] text-emerald-900 dark:bg-emerald-950 dark:text-emerald-200">{{ change.to|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
                                                                {% else %}
                                                                    <span class="rounded bg-emerald-50 px-1.5 py-0.5 font-mono text-emerald-900 dark:bg-emerald-950 dark:text-emerald-200">{{ change.to }}</span>
                                                                {% endif %}
                                                            </td>
                                                        </tr>
                                                    {% endfor %}
                                                </tbody>
                                            </table>
                                        </div>
                                    {% endif %}
                                    <details class="text-xs" {% if ev.details.changes is not defined %}open{% endif %}>
                                        <summary class="cursor-pointer text-slate-500 hover:text-slate-800 dark:text-slate-400 dark:hover:text-slate-200">Raw payload</summary>
                                        <pre class="mt-2 overflow-x-auto rounded bg-white p-3 dark:bg-slate-900">{{ ev.details|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre>
                                    </details>
                                </td>
                            </tr>
                        {% endif %}
                    {% else %}
                        <tr><td colspan="6" class="px-4 py-6 text-center text-slate-400">No events match these filters.</td></tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        {% if list.total > list.page_size %}
            {% set total_pages = (list.total // list.page_size) + (list.total % list.page_size > 0 ? 1 : 0) %}
            <nav class="mt-4 flex items-center justify-between text-sm">
                <span class="text-slate-500 dark:text-slate-400">Page {{ page }} of {{ total_pages }}</span>
                <div class="flex gap-2">
                    {% set prev_qs = filters|merge({'page': page - 1}) %}
                    {% set next_qs = filters|merge({'page': page + 1}) %}
                    {% if page > 1 %}
                        <a href="/app/audit?{{ prev_qs|url_encode }}" class="rounded-md border border-slate-300 px-3 py-1.5 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">‹ Prev</a>
                    {% endif %}
                    {% if page < total_pages %}
                        <a href="/app/audit?{{ next_qs|url_encode }}" class="rounded-md border border-slate-300 px-3 py-1.5 hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800">Next ›</a>
                    {% endif %}
                </div>
            </nav>
        {% endif %}
    {% endif %}
</div>
{% endblock %}
