<?php

namespace App\Services\Audit;

use App\Contracts\AuditLogRepositoryContract;
use App\Models\AuditLog;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class AuditLogService
{
    public function __construct(
        private readonly AuditLogRepositoryContract $auditLogs,
    ) {}

    public function paginate(array $filters = [], int $perPage = 25): LengthAwarePaginator
    {
        return $this->auditLogs->paginate($filters, $perPage);
    }

    /**
     * @param  array<string, mixed>  $properties
     */
    public function log(string $action, ?Model $subject = null, array $properties = [], ?string $ipAddress = null): AuditLog
    {
        return $this->auditLogs->create([
            'user_id' => Auth::id(),
            'action' => $action,
            'subject_type' => $subject ? $subject->getMorphClass() : null,
            'subject_id' => $subject?->getKey(),
            'properties' => $properties,
            'ip_address' => $ipAddress ?? request()->ip(),
        ]);
    }
}
