<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\FileStore;

class ActivityLogService
{
    public function log(string $action, string $description, ?int $userId = null): void
    {
        $store = new FileStore(storage_path('data/activity_logs.json'));

        $store->insert([
            'user_id' => $userId,
            'action' => $action,
            'description' => $description,
            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
            'created_at' => date('c'),
        ]);
    }

    public function recent(int $limit = 6): array
    {
        $store = new FileStore(storage_path('data/activity_logs.json'));
        $items = $store->all();

        usort($items, fn (array $a, array $b): int => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));

        return array_slice(array_values($items), 0, $limit);
    }
}
