<?php

namespace Modules\NX600Lab\Entities;

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

class NxTestSession extends Model
{
    protected $table = 'nx_test_sessions';

    protected $fillable = [
        'business_id', 'sample_no', 'patient_id', 'patient_name', 'test_condition',
        'test_date', 'test_time', 'sample_type', 'species', 'sex', 'age',
        'sample_position', 'operator_id', 'emergency_test', 'analyzer_id',
        'slide_lot', 'valid_term', 'comm_type', 'device_ip',
        'contact_id', 'vc_pet_id',
    ];

    protected $casts = [
        'test_date'      => 'date',
        'species'        => 'integer',
        'sex'            => 'integer',
        'age'            => 'integer',
        'emergency_test' => 'boolean',
    ];

    public function testResults(): HasMany
    {
        return $this->hasMany(NxTestResult::class, 'test_session_id');
    }

    public function worklist(): BelongsTo
    {
        return $this->belongsTo(NxWorklist::class, 'sample_no', 'sample_no');
    }

    /**
     * The VetClinic pet this session belongs to (synced mode only).
     */
    public function pet()
    {
        return $this->belongsTo(\Modules\VetClinic\Entities\VcPet::class, 'vc_pet_id');
    }

    public function getSpeciesNameAttribute(): string
    {
        $map = NxModuleSetting::speciesMap($this->business_id);
        return $map[$this->species] ?? "Species #{$this->species}";
    }

    public function getSexLabelAttribute(): string
    {
        return match ($this->sex) {
            0 => 'Male',
            1 => 'Female',
            default => 'Unknown',
        };
    }

    public function getSampleTypeLabelAttribute(): string
    {
        return match ($this->sample_type) {
            'W' => 'Whole Blood',
            'P' => 'Plasma/Serum',
            'U' => 'Urine',
            default => 'Unknown',
        };
    }

    public function getIsAbnormalAttribute(): bool
    {
        return $this->testResults()->where('is_abnormal', true)->exists();
    }
}
