<?php
require __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Audit\AuditLogger;
use Gestoreasy\Core\Tenant\ConnectionManager;

$tenant = $argv[1] ?? 'default';
$resource = $argv[2] ?? null; // e.g., 'products' ou 'product_meta'
$limit = isset($argv[3]) ? (int)$argv[3] : 50;

// Configurar tenant atual (se aplicável)
putenv("TENANT_ID={$tenant}");

try {
    $pdo = ConnectionManager::forTenant();
    // Verificar existência da tabela audit_logs
    $stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'audit_logs'");
    $stmt->execute();
    $exists = ((int)($stmt->fetch()['c'] ?? 0)) > 0;
    if (!$exists) {
        fwrite(STDERR, "[audit] Tabela audit_logs não existe no tenant '{$tenant}'.\n");
        exit(2);
    }
} catch (Throwable $e) {
    fwrite(STDERR, "[audit] Erro ao conectar/verificar DB: {$e->getMessage()}\n");
    exit(1);
}

// Buscar logs: se nenhum resource for passado, pegar produtos e metas
$resources = $resource ? [$resource] : ['products', 'product_meta'];

foreach ($resources as $res) {
    try {
        $logs = AuditLogger::getAuditTrail($res, null, $limit);
        echo "=== AUDIT '{$res}' (últimos {$limit}) ===\n";
        foreach ($logs as $log) {
            $id = $log['id'] ?? '?';
            $action = $log['action'] ?? '?';
            $rid = $log['resource_id'] ?? null;
            $created = $log['created_at'] ?? '';
            $user = $log['user_email'] ?? ($log['user_id'] ?? null);
            $changes = isset($log['metadata']['changes']) ? json_encode($log['metadata']['changes']) : null;
            echo "[#{$id}] {$created} action={$action} res_id=" . ($rid ?? 'null') . " user=" . ($user ?? 'null') . "\n";
            if ($changes) {
                echo "  changes: {$changes}\n";
            }
            if (!empty($log['new_data'])) {
                $keys = implode(',', array_keys($log['new_data']));
                echo "  new_keys: {$keys}\n";
            }
        }
        echo "\n";
    } catch (Throwable $e) {
        fwrite(STDERR, "[audit] Falha ao obter trilha para '{$res}': {$e->getMessage()}\n");
    }
}

echo "[audit] Concluído para tenant '{$tenant}'.\n";