<?php

namespace App\Services;

use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;

class ActivityLogService
{
    public function log(
        string $action,
        string $module,
        Model $model,
        ?string $description = null,
        array $oldValues = [],
        array $newValues = []
    ): ActivityLog {
        return ActivityLog::create([
            'user_id'        => auth()->id(),
            'action'         => $action,
            'module'         => $module,
            'reference_type' => get_class($model),
            'reference_id'   => $model->id,
            'description'    => $description,
            'old_values'     => !empty($oldValues) ? $oldValues : null,
            'new_values'     => !empty($newValues) ? $newValues : null,
            'ip_address'     => request()->ip(),
        ]);
    }

    public function logAction(
        string $action,
        string $module,
        string $referenceType,
        ?int $referenceId,
        ?string $description = null,
        array $oldValues = [],
        array $newValues = []
    ): ActivityLog {
        return ActivityLog::create([
            'user_id'        => auth()->id(),
            'action'         => $action,
            'module'         => $module,
            'reference_type' => $referenceType,
            'reference_id'   => $referenceId,
            'description'    => $description,
            'old_values'     => !empty($oldValues) ? $oldValues : null,
            'new_values'     => !empty($newValues) ? $newValues : null,
            'ip_address'     => request()->ip(),
        ]);
    }

    public function getForModel(Model $model, int $limit = 50)
    {
        return ActivityLog::where('reference_type', get_class($model))
            ->where('reference_id', $model->id)
            ->latest()
            ->limit($limit)
            ->get();
    }

    public function getForModule(string $module, int $limit = 50)
    {
        return ActivityLog::with('user')
            ->forModule($module)
            ->latest()
            ->limit($limit)
            ->get();
    }
}
