<?php

declare(strict_types=1);

namespace App\Models;

use App\Support\DberpAuditDisplay;
use DBCore\Audit\Models\AuditLog;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpAuditLog extends AuditLog
{
    /**
     * @var list<string>
     */
    protected $fillable = [
        'user_id',
        'action',
        'auditable_type',
        'auditable_id',
        'old_values',
        'new_values',
        'ip_address',
        'user_agent',
        'correlation_id',
    ];

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

    public function getOldValuesSummaryAttribute(): string
    {
        return $this->summarizeAuditValues($this->old_values);
    }

    public function getNewValuesSummaryAttribute(): string
    {
        return $this->summarizeAuditValues($this->new_values);
    }

    /**
     * @param  array<string, mixed>|null  $values
     */
    private function summarizeAuditValues(?array $values): string
    {
        if (empty($values)) {
            return '-';
        }

        return collect($values)
            ->take(4)
            ->map(function (mixed $value, string $key): string {
                return sprintf(
                    '%s：%s',
                    DberpAuditDisplay::snapshotKeyLabel($key, $this->auditable_type),
                    DberpAuditDisplay::snapshotValueSummary($value),
                );
            })
            ->implode('；');
    }
}
