<?php

namespace Modules\NX600Lab\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class NxTestResult extends Model
{
    protected $table = 'nx_test_results';

    protected $fillable = [
        'test_session_id', 'test_name', 'base_name', 'sample_suffix',
        'equality', 'result', 'unit', 'dilution_factor',
        'ref_lower', 'ref_upper',
        'warn_high', 'warn_low', 'warn_out_of_range', 'warn_slide_expired',
        'warn_temp_error', 'warn_photometer_error', 'warn_high_value',
        'warn_calc_error', 'warn_unspotted', 'raw_warning', 'is_abnormal',
    ];

    protected $casts = [
        'dilution_factor'       => 'integer',
        'warn_high'             => 'boolean',
        'warn_low'              => 'boolean',
        'warn_out_of_range'     => 'boolean',
        'warn_slide_expired'    => 'boolean',
        'warn_temp_error'       => 'boolean',
        'warn_photometer_error' => 'boolean',
        'warn_high_value'       => 'boolean',
        'warn_calc_error'       => 'boolean',
        'warn_unspotted'        => 'boolean',
        'is_abnormal'           => 'boolean',
    ];

    public function testSession(): BelongsTo
    {
        return $this->belongsTo(NxTestSession::class, 'test_session_id');
    }

    public function getResultNumericAttribute(): ?float
    {
        return is_numeric($this->result) ? (float) $this->result : null;
    }

    public function getStatusBadgeAttribute(): string
    {
        if ($this->warn_calc_error || $this->warn_unspotted) {
            return 'error';
        }
        if ($this->warn_high || $this->warn_low || $this->warn_out_of_range || $this->warn_high_value) {
            return 'abnormal';
        }
        if ($this->warn_slide_expired || $this->warn_temp_error || $this->warn_photometer_error) {
            return 'warning';
        }
        return 'normal';
    }

    public function getResultDisplayAttribute(): string
    {
        $prefix = in_array($this->equality, ['>', '<']) ? $this->equality : '';
        return $prefix . trim($this->result ?? '');
    }
}
