<?php

declare(strict_types=1);

use App\Infrastructure\Db\Migrations\BaseMigration;

/**
 * SEC_REVIEW F11: every audit row gets an `actor_via` discriminator
 * recording how the actor reached the API.
 *
 * Values:
 *   - `oidc`         — service token + impersonation, user.is_local = 0
 *   - `local`        — service token + impersonation, user.is_local = 1
 *   - `admin-token`  — bearer of an admin-kind token
 *   - `service`      — service token without impersonation (auth/upsert)
 *   - `reporter`     — reporter-kind token (public report endpoint)
 *   - `consumer`     — consumer-kind token (public blocklist)
 *   - `system`       — no principal (jobs, system-internal emits)
 *
 * The existing `actor_kind` column already encodes most of this, but
 * conflates "user via OIDC browser" and "user via local-admin form": both
 * surface as `actor_kind=user`. With `actor_via` populated, an auditor
 * filtering on `actor_via='local'` can scope reviews to a specific
 * sign-in path without joining `users` on every row.
 *
 * Backfill: NULL on existing rows. The column is queryable but optional;
 * the API surfaces it on read but does not require it on filter.
 */
final class AddActorViaToAuditLog extends BaseMigration
{
    public function up(): void
    {
        $this->table('audit_log')
            ->addColumn('actor_via', 'string', ['limit' => 16, 'null' => true, 'after' => 'actor_id'])
            ->update();

        $this->execute('CREATE INDEX idx_audit_actor_via ON audit_log (actor_via)');
    }

    public function down(): void
    {
        if ($this->isMysql()) {
            $this->execute('DROP INDEX idx_audit_actor_via ON audit_log');
        } else {
            $this->execute('DROP INDEX IF EXISTS idx_audit_actor_via');
        }

        $this->table('audit_log')
            ->removeColumn('actor_via')
            ->update();
    }
}
