<?php

namespace App\Services;

use App\Models\ActivityLog;
use Illuminate\Http\Request;

class ActivityLogger
{
    public function log(string $event, mixed $subject = null, array $context = [], ?Request $request = null, ?int $familyId = null): void
    {
        $userId = $request?->user()?->id;

        if ($familyId === null && $subject && property_exists($subject, 'family_id')) {
            $familyId = $subject->family_id;
        }

        $data = [
            'user_id' => $userId,
            'family_id' => $familyId,
            'event' => $event,
            'subject_type' => $subject ? $subject::class : null,
            'subject_id' => method_exists($subject, 'getKey') ? $subject->getKey() : null,
            'context' => empty($context) ? null : $context,
            'ip_address' => $request?->ip(),
        ];

        ActivityLog::create($data);
    }
}
