<?php

namespace Modules\ClinicLab\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Modules\LabCore\Entities\LabWorklist;

/**
 * A tracked specimen (barcode + status chain) wrapping a LabCore worklist order
 * or an outreach / manual order. business_id scoped.
 */
class CllSpecimen extends Model
{
    protected $table = 'cll_specimens';

    protected $fillable = [
        'business_id', 'specimen_no', 'worklist_id', 'clc_order_item_id',
        'patient_id', 'contact_id', 'catalog_id', 'specimen_type',
        'collected_at', 'collected_by', 'received_at', 'received_by',
        'status', 'rejected_reason', 'rejection_notes',
    ];

    protected $casts = [
        'collected_at' => 'datetime',
        'received_at'  => 'datetime',
    ];

    /** Human-facing labels for the status chain. */
    public const STATUSES = [
        'awaiting_collection' => 'Awaiting collection',
        'collected'           => 'Collected',
        'in_transit'          => 'In transit',
        'received'            => 'Received',
        'processing'          => 'Processing',
        'resulted'            => 'Resulted',
        'rejected'            => 'Rejected',
        'disposed'            => 'Disposed',
    ];

    public const REJECT_REASONS = [
        'hemolyzed'           => 'Hemolyzed',
        'clotted'             => 'Clotted',
        'insufficient_volume' => 'Insufficient volume',
        'wrong_container'     => 'Wrong container',
        'mislabeled'          => 'Mislabeled',
        'expired'             => 'Expired',
        'other'               => 'Other',
    ];

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

    public function catalog(): BelongsTo
    {
        return $this->belongsTo(CllTestCatalog::class, 'catalog_id');
    }

    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }
}
