<?php

namespace App\Services\Audit;

use App\Models\AuditLog;

class AuditLogService
{
    public function list(array $filters = [])
    {
        $query = AuditLog::query();

        if (!empty($filters['module'])) {
            $query->where('module', $filters['module']);
        }

        if (!empty($filters['action'])) {
            $query->where('action', $filters['action']);
        }

        if (!empty($filters['user_id'])) {
            $query->where('user_id', $filters['user_id']);
        }

        if (!empty($filters['tenant_id'])) {
            $query->where('tenant_id', $filters['tenant_id']);
        }

        return $query
            ->latest('id')
            ->paginate(
                $filters['per_page'] ?? 20
            );
    }

    public function detail($id)
    {
        return AuditLog::findOrFail($id);
    }

    public static function log(
        string $module,
        string $action,
        ?string $tableName = null,
        ?int $recordId = null,
        ?array $oldValues = null,
        ?array $newValues = null,
        ?string $description = null
    ): void {

        AuditLog::create([
            'user_id'     => auth()->id(),
            'tenant_id'   => request()->header('X-Tenant-Id'),

            'module'      => $module,
            'action'      => $action,

            'table_name'  => $tableName,
            'record_id'   => $recordId,

            'old_values'  => $oldValues,
            'new_values'  => $newValues,

            'ip_address'  => request()->ip(),
            'user_agent'  => request()->userAgent(),

            'description' => $description,
        ]);
    }
}