<?php

namespace Modules\LabCore\Entities;

use Illuminate\Database\Eloquent\Model;

class LabAnalyteMap extends Model
{
    protected $table = 'lab_analyte_map';

    protected $fillable = [
        'business_id', 'vendor', 'model', 'analyte_code', 'canonical_name',
        'display_name', 'unit', 'species', 'ref_lower', 'ref_upper',
        'category', 'sort_order',
    ];

    protected $casts = [
        'sort_order' => 'integer',
    ];

    /**
     * Resolve the canonical mapping for a vendor analyte code. Prefers a
     * per-business override, then the species-specific row, then any global.
     */
    public static function resolve(string $vendor, string $code, ?string $species = null, ?int $businessId = null): ?self
    {
        $query = static::where('vendor', $vendor)->where('analyte_code', $code);

        return (clone $query)->where('business_id', $businessId)->where('species', $species)->first()
            ?? (clone $query)->whereNull('business_id')->where('species', $species)->first()
            ?? (clone $query)->whereNull('business_id')->whereNull('species')->first()
            ?? (clone $query)->first();
    }
}
