<?php

namespace Modules\LabCore\Entities;

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

class LabTestSession extends Model
{
    protected $table = 'lab_test_sessions';

    protected $fillable = [
        'uuid', 'business_id', 'agent_id', 'device_id', 'vendor',
        'sample_no', 'patient_id', 'patient_name', 'test_condition',
        'test_date', 'test_time', 'sample_type', 'species', 'species_code',
        'sex', 'age', 'operator_id', 'analyzer_id', 'device_ip', 'source',
        'meta', 'contact_id', 'vc_pet_id',
    ];

    protected $casts = [
        'test_date' => 'date',
        'meta'      => 'array',
        'age'       => 'integer',
    ];

    protected static function booted(): void
    {
        static::creating(function (LabTestSession $session) {
            if (empty($session->uuid)) {
                $session->uuid = (string) Str::uuid();
            }
        });
    }

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

    public function device(): BelongsTo
    {
        return $this->belongsTo(LabDevice::class, 'device_id');
    }

    public function agent(): BelongsTo
    {
        return $this->belongsTo(LabAgent::class, 'agent_id');
    }

    public function pet(): BelongsTo
    {
        return $this->belongsTo(\Modules\VetClinic\Entities\VcPet::class, 'vc_pet_id');
    }

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