<?php
declare(strict_types=1);

namespace App\Repositories;

use App\Json\FileStore;

class JsonAuditRepository implements AuditRepository
{
    public function __construct(private FileStore $store) {}

    public function log(string $staffId, string $action, string $targetType, string $targetId, array $metadata = []): array
    {
        $entry = [
            'id'          => uuid(),
            'staff_id'    => $staffId,
            'action'      => $action,
            'target_type' => $targetType,
            'target_id'   => $targetId,
            'metadata'    => $metadata,
            'ip'          => $_SERVER['REMOTE_ADDR'] ?? null,
            'created_at'  => now_iso(),
        ];
        $this->store->transaction(function ($d) use ($entry) {
            $d['entries'] = $d['entries'] ?? [];
            $d['entries'][] = $entry;
            return $d;
        });
        return $entry;
    }

    public function all(array $filters = [], int $limit = 200): array
    {
        $d = $this->store->read();
        $list = $d['entries'] ?? [];
        if (!empty($filters['staff_id'])) {
            $list = array_values(array_filter($list, fn($e) => ($e['staff_id'] ?? '') === $filters['staff_id']));
        }
        if (!empty($filters['action'])) {
            $list = array_values(array_filter($list, fn($e) => ($e['action'] ?? '') === $filters['action']));
        }
        usort($list, fn($a, $b) => strcmp((string)($b['created_at'] ?? ''), (string)($a['created_at'] ?? '')));
        return array_slice($list, 0, $limit);
    }
}
