<?php

namespace App\Models\Audit;

use Illuminate\Database\Eloquent\Model;

class TriggerAuditLog extends Model
{
    public $timestamps = false;

    protected $table = 'trigger_audit_logs';

    protected $fillable = [
        'table_name',
        'row_id',
        'dml_type',
        'old_values',
        'new_values',
        'changed_columns',
        'tenant_id',
        'actor_id',
        'session_info',
        'db_user',
        'created_at',
    ];

    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 디코딩
     */
    public function getSessionInfoAttribute($value): ?array
    {
        if (is_string($value)) {
            return json_decode($value, true);
        }

        return $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 scopeForTenant($query, int $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }
}
