<?php

namespace App\Models\Concerns;

use App\Models\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

trait LogsActivity
{
    protected static function bootLogsActivity()
    {
        static::created(function ($model) {
            $model->recordActivity('created');
        });

        static::updated(function ($model) {
            if ($model->isDirty()) {
                $model->recordActivity('updated');
            }
        });

        static::deleted(function ($model) {
            $model->recordActivity('deleted');
        });
    }

    public function recordActivity(string $action)
    {
        try {
            $user = Auth::user();
            $userId = $user ? $user->id : null;

            $description = method_exists($this, 'getActivityLogDescription')
                ? $this->getActivityLogDescription($action)
                : sprintf('%s %s', class_basename($this), $action);

            $properties = method_exists($this, 'getActivityLogProperties')
                ? $this->getActivityLogProperties($action)
                : $this->getDefaultActivityLogProperties($action);

            ActivityLog::create([
                'user_id'      => $userId,
                'loggable_id'  => $this->getKey(),
                'loggable_type'=> get_class($this),
                'action'       => $action,
                'description'  => $description,
                'properties'   => $properties,
                'ip_address'   => Request::ip(),
                'user_agent'   => Request::userAgent(),
            ]);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to record activity log: ' . $e->getMessage());
        }
    }

    protected function getDefaultActivityLogProperties(string $action): array
    {
        if ($action === 'updated') {
            return [
                'old' => array_intersect_key($this->getOriginal(), $this->getDirty()),
                'attributes' => $this->getDirty(),
            ];
        }

        return ['attributes' => $this->attributesToArray()];
    }
}
