<?php

namespace Modules\NX600Lab\Adapters;

use Modules\NX600Lab\Contracts\LabAdapterInterface;
use Modules\NX600Lab\Entities\NxModuleSetting;
use Modules\NX600Lab\Entities\NxTestSession;
use Modules\NX600Lab\Entities\NxWorklist;

/**
 * Reference implementation of LabAdapterInterface for the in-house NX600
 * analyzer. Wraps the existing worklist/result entities.
 */
class Nx600Adapter implements LabAdapterInterface
{
    public function __construct(private ?int $businessId = null) {}

    public function key(): string         { return 'nx600'; }
    public function displayName(): string { return 'NX600 in-house analyzer'; }

    public function pushOrder(array $order): string
    {
        $wl = NxWorklist::create([
            'business_id' => $order['business_id'] ?? $this->businessId,
            'pet_id'      => $order['pet_id']      ?? null,
            'doctor_id'   => $order['doctor_id']   ?? null,
            'priority'    => $order['priority']    ?? 'routine',
            'status'      => 'pending',
            'requested_tests' => is_array($order['requested_tests'] ?? null)
                ? json_encode($order['requested_tests'])
                : null,
        ]);
        return 'nx600:' . $wl->id;
    }

    public function pullResults(string $orderRef): array
    {
        if (!str_starts_with($orderRef, 'nx600:')) return [];
        $wlId = (int) substr($orderRef, 6);

        // Pull most recent session for this worklist; results table varies by
        // session schema — return an empty list if unmapped.
        $session = NxTestSession::where('worklist_id', $wlId)->latest('id')->first();
        if (!$session) return [];

        return $session->results()->get(['analyte', 'value', 'unit', 'flag'])->toArray();
    }

    public function listAnalytes(): array
    {
        // NX600 panel — small static set; real catalogue lives on the device.
        return [
            ['code' => 'WBC', 'name' => 'White blood cells', 'category' => 'CBC'],
            ['code' => 'RBC', 'name' => 'Red blood cells',   'category' => 'CBC'],
            ['code' => 'HGB', 'name' => 'Hemoglobin',         'category' => 'CBC'],
            ['code' => 'PLT', 'name' => 'Platelets',          'category' => 'CBC'],
            ['code' => 'GLU', 'name' => 'Glucose',            'category' => 'Chemistry'],
            ['code' => 'BUN', 'name' => 'Blood urea nitrogen','category' => 'Chemistry'],
            ['code' => 'CRE', 'name' => 'Creatinine',         'category' => 'Chemistry'],
        ];
    }

    public function ping(): bool
    {
        // The NX600 lives on the LAN and either is reachable or isn't; reuse
        // the existing settings flag as the truthy hint.
        if (!$this->businessId) return true;
        return (string) NxModuleSetting::get($this->businessId, 'device_connected', '1') === '1';
    }
}
