<?php

namespace App\Models\Audit;

use Illuminate\Database\Eloquent\Model;

class TriggerAuditLog extends Model
{
    protected $table = 'trigger_audit_logs';

    public $timestamps = false;

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

    /**
     * changed_columns에서 NULL 값 제거
     */
    public function getChangedColumnsAttribute($value): ?array
    {
        $decoded = is_string($value) ? json_decode($value, true) : $value;
        if (! is_array($decoded)) {
            return null;
        }

        return array_values(array_filter($decoded, fn ($v) => $v !== null));
    }

    /**
     * session_info JSON → array
     */
    public function getSessionInfoAttribute($value): ?array
    {
        if (! $value) {
            return null;
        }

        return is_string($value) ? json_decode($value, true) : $value;
    }

    public function scopeForTable($query, string $tableName)
    {
        return $query->where('table_name', $tableName);
    }

    public function scopeForRecord($query, string $tableName, string $rowId)
    {
        return $query->where('table_name', $tableName)->where('row_id', $rowId);
    }

    public function scopeForOperation($query, string $operationId)
    {
        return $query->where('operation_id', $operationId);
    }
}
