<?php

namespace App\Services\Audit;

use App\Models\Audit\AuditLog;
use App\Services\Service;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AuditLogService extends Service
{
    public function paginate(array $filters): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

        $page = (int) ($filters['page'] ?? 1);
        $size = (int) ($filters['size'] ?? 20);
        $sort = $filters['sort'] ?? 'created_at';
        $order = $filters['order'] ?? 'desc';

        $q = AuditLog::query()->where('tenant_id', $tenantId);

        if (! empty($filters['target_type'])) {
            $q->where('target_type', $filters['target_type']);
        }
        if (! empty($filters['target_id'])) {
            $q->where('target_id', (int) $filters['target_id']);
        }
        if (! empty($filters['action'])) {
            $q->where('action', $filters['action']);
        }
        if (! empty($filters['actor_id'])) {
            $q->where('actor_id', (int) $filters['actor_id']);
        }
        if (! empty($filters['from'])) {
            $q->where('created_at', '>=', $filters['from']);
        }
        if (! empty($filters['to'])) {
            $q->where('created_at', '<=', $filters['to']);
        }

        return $q->orderBy($sort, $order)->paginate($size, ['*'], 'page', $page);
    }
}
