<?php

namespace App\Traits;

use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;

trait LogsActivity
{
    /**
     * Boot the trait and register model events.
     */
    protected static function bootLogsActivity(): void
    {
        static::created(function (Model $model) {
            self::logActivity($model, 'created');
        });

        static::updated(function (Model $model) {
            self::logActivity($model, 'updated');
        });

        static::deleted(function (Model $model) {
            self::logActivity($model, 'deleted');
        });
    }

    /**
     * Log the activity to the database.
     */
    protected static function logActivity(Model $model, string $action): void
    {
        // Don't log if no user is authenticated (e.g. CLI or system tasks)
        // unless you want to log system actions too.
        if (!Auth::check()) {
            return;
        }

        $properties = null;

        if ($action === 'updated') {
            $properties = [
                'old' => array_intersect_key($model->getOriginal(), $model->getDirty()),
                'new' => $model->getDirty(),
            ];

            // Remove timestamps and sensitive fields if needed
            unset($properties['old']['updated_at'], $properties['new']['updated_at']);
        } elseif ($action === 'deleted') {
            $properties = ['attributes' => $model->getAttributes()];
        } elseif ($action === 'created') {
            $properties = ['attributes' => $model->getAttributes()];
        }

        ActivityLog::create([
            'user_id'      => Auth::id(),
            'action'       => $action,
            'subject_id'   => $model->getKey(),
            'subject_type' => get_class($model),
            'description'  => self::getActivityDescription($model, $action),
            'properties'   => $properties,
            'ip_address'   => Request::ip(),
            'user_agent'   => Request::userAgent(),
        ]);
    }

    /**
     * Generate a human-readable description for the activity.
     */
    protected static function getActivityDescription(Model $model, string $action): string
    {
        $modelName = class_basename($model);
        $identifier = $model->title ?? $model->name ?? $model->id;

        return "{$action} {$modelName}: \"{$identifier}\"";
    }
}
