<?php

namespace App\Traits;

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

trait Auditable
{
    /**
     * Boot the auditable trait
     */
    protected static function bootAuditable()
    {
        static::created(function ($model) {
            self::logActivity('created', $model, null, $model->getAttributes());
        });

        static::updated(function ($model) {
            $changes = $model->getChanges();
            $original = $model->getOriginal();

            // Only log if there are actual changes
            if (!empty($changes)) {
                $old = [];
                $new = [];

                foreach ($changes as $key => $value) {
                    if (isset($original[$key])) {
                        $old[$key] = $original[$key];
                    }
                    $new[$key] = $value;
                }

                self::logActivity('updated', $model, $old, $new);
            }
        });

        static::deleted(function ($model) {
            self::logActivity('deleted', $model, $model->getAttributes(), null);
        });
    }

    /**
     * Log activity
     */
    protected static function logActivity($action, $model, $oldValues, $newValues)
    {
        try {
            if (!Auth::check()) {
                return;
            }

            $user = Auth::user();

            // Only log for admin and super_admin users
            if (!in_array($user->role, ['admin', 'super_admin'])) {
                return;
            }

            ActivityLog::create([
                'user_id' => $user->id,
                'action' => $action,
                'model_type' => class_basename($model),
                'model_id' => $model->id ?? null,
                'old_values' => $oldValues,
                'new_values' => $newValues,
                'description' => self::buildDescription($action, $model, $oldValues, $newValues),
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ]);
        } catch (\Exception $e) {
            // Silently fail to not interrupt the main operation
            \Log::error('Activity logging failed: ' . $e->getMessage());
        }
    }

    /**
     * Build a descriptive message
     */
    protected static function buildDescription($action, $model, $oldValues, $newValues)
    {
        $modelName = class_basename($model);

        return match ($action) {
            'created' => "Created a new {$modelName}",
            'updated' => "Updated {$modelName}",
            'deleted' => "Deleted {$modelName}",
            default => "{$action} {$modelName}",
        };
    }
}
