<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SystemLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'action', 'entity_type', 'entity_id',
        'old_values', 'new_values', 'ip_address'
    ];

    protected $casts = [
        'old_values' => 'array',
        'new_values' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function scopeByAction($query, $action)
    {
        return $query->where('action', $action);
    }

    public function scopeByEntity($query, $type, $id = null)
    {
        $q = $query->where('entity_type', $type);
        if ($id)
            $q->where('entity_id', $id);
        return $q;
    }

    public static function logCreate($userId, $entityType, $entityId, $newValues, $ip = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => 'create',
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'new_values' => $newValues,
            'ip_address' => $ip ?? request()->ip()
        ]);
    }

    public static function logUpdate($userId, $entityType, $entityId, $oldValues, $newValues, $ip = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => 'update',
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'ip_address' => $ip ?? request()->ip()
        ]);
    }

    public static function logDelete($userId, $entityType, $entityId, $oldValues, $ip = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => 'delete',
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'old_values' => $oldValues,
            'ip_address' => $ip ?? request()->ip()
        ]);
    }

    public static function logRevoke($userId, $entityType, $entityId, $oldValues, $newValues, $ip = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => 'revoke',
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'ip_address' => $ip ?? request()->ip()
        ]);
    }

    public static function logExtend($userId, $entityType, $entityId, $oldValues, $newValues, $ip = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => 'extend',
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'ip_address' => $ip ?? request()->ip()
        ]);
    }
}