<?php

namespace Modules\LabCore\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LabCommunicationLog extends Model
{
    use SoftDeletes;

    protected $table = 'lab_communication_logs';

    protected $fillable = [
        'agent_id', 'device_id', 'vendor', 'level', 'category', 'direction',
        'device_ip', 'sample_no', 'message', 'raw_message', 'context',
    ];

    protected $casts = [
        'context' => 'array',
    ];

    /**
     * @param array{agent_id?:int,device_id?:int,vendor?:string,direction?:string,device_ip?:string,sample_no?:string,raw_message?:string,context?:array} $extra
     */
    public static function write(string $level, string $message, string $category = 'system', array $extra = []): void
    {
        static::create(array_merge([
            'level'    => $level,
            'category' => $category,
            'message'  => $message,
        ], array_intersect_key($extra, array_flip([
            'agent_id', 'device_id', 'vendor', 'direction',
            'device_ip', 'sample_no', 'raw_message', 'context',
        ]))));
    }

    public static function info(string $message, string $category = 'system', array $extra = []): void
    {
        static::write('info', $message, $category, $extra);
    }

    public static function success(string $message, string $category = 'system', array $extra = []): void
    {
        static::write('success', $message, $category, $extra);
    }

    public static function warning(string $message, string $category = 'system', array $extra = []): void
    {
        static::write('warning', $message, $category, $extra);
    }

    public static function error(string $message, string $category = 'system', array $extra = []): void
    {
        static::write('error', $message, $category, $extra);
    }

    public function getLevelBadgeAttribute(): string
    {
        return match ($this->level) {
            'success' => 'bg-success',
            'warning' => 'bg-warning text-dark',
            'error'   => 'bg-danger',
            default   => 'bg-info text-dark',
        };
    }
}
