<?php

namespace App\Services\Audit;

use App\Models\ActivityLog;
use App\Models\Business;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class ActivityLogger
{
    public function log(
        ?User $actor,
        string $event,
        ?string $description = null,
        Model|Business|null $subject = null,
        array $properties = [],
        ?Request $request = null,
        ?Business $business = null
    ): ActivityLog {
        $resolvedBusiness = $business
            ?? ($subject instanceof Business ? $subject : null)
            ?? ($subject && array_key_exists('business_id', $subject->getAttributes()) ? $subject->business : null);

        return ActivityLog::query()->create([
            'business_id' => $resolvedBusiness?->id,
            'user_id' => $actor?->id,
            'event' => $event,
            'subject_type' => $subject ? $subject::class : null,
            'subject_id' => $subject?->getKey(),
            'description' => $description,
            'ip_address' => $request?->ip(),
            'user_agent' => $request?->userAgent(),
            'properties' => $properties,
        ]);
    }
}
