<?php

namespace Modules\ClinicWhatsApp\Console;

use Carbon\Carbon;
use Illuminate\Console\Command;

/**
 * Notify a ClinicCore patient over WhatsApp when their LabCore lab results
 * arrive — closing the loop: order via ClinicLab -> results return -> patient
 * pinged. Idempotent per session (WaSender dedupe_key). No-ops gracefully if
 * LabCore is absent.
 */
class ClinicWaResultNotify extends Command
{
    protected $signature = 'clinicwa:notify-lab-results
        {--days=7 : Only sessions with results from the last N days}
        {--business= : Limit to a single business id}
        {--dry : Report what would be sent without sending}';

    protected $description = 'WhatsApp patients when their clinic lab results are ready';

    public function handle(): int
    {
        $sessionClass = \Modules\LabCore\Entities\LabTestSession::class;
        $senderClass  = \Modules\WhatsApp\Entities\Services\WaSender::class;
        if (! class_exists($sessionClass) || ! class_exists($senderClass)) {
            $this->error('LabCore or WhatsApp module not available.');
            return self::FAILURE;
        }
        $sender   = new $senderClass();
        $settingC = \Modules\WhatsApp\Entities\WaSetting::class;
        $patientC = \Modules\ClinicCore\Entities\ClcPatient::class;

        $dry    = (bool) $this->option('dry');
        $cutoff = Carbon::today()->subDays(max(0, (int) $this->option('days')))->toDateString();

        $businessIds = $this->option('business')
            ? [(int) $this->option('business')]
            : \Illuminate\Support\Facades\DB::table('business')->pluck('id')->all();

        $count = 0;
        foreach ($businessIds as $biz) {
            if (class_exists($settingC) && $settingC::get($biz, 'enabled', '1') !== '1') {
                continue;
            }

            $sessions = $sessionClass::has('results')
                ->whereNotNull('clc_patient_id')
                ->where('business_id', $biz)
                ->where('test_date', '>=', $cutoff)
                ->get(['id', 'uuid', 'sample_no', 'clc_patient_id', 'patient_name']);

            foreach ($sessions as $s) {
                $patient = $patientC::with('contact')->find($s->clc_patient_id);
                $mobile  = optional(optional($patient)->contact)->mobile;
                if (! $mobile) continue;

                $name = $s->patient_name ?: (optional($patient)->patient_name ?: optional(optional($patient)->contact)->name);
                $body = "Good news — {$name}'s lab results (sample {$s->sample_no}) are ready. Please contact the clinic to review them.";

                if ($dry) {
                    $this->line("  [result] biz {$biz} -> {$mobile}: {$body}");
                } else {
                    $sender->send([
                        'business_id' => $biz, 'to' => $mobile, 'body' => $body,
                        'source' => 'clinic_lab_result', 'dedupe_key' => "clc-lab-result:{$s->uuid}",
                    ]);
                }
                $count++;
            }
        }

        $verb = $dry ? 'would notify' : 'queued';
        $this->info("ClinicWhatsApp lab-result notifications {$verb}: {$count}.");
        return self::SUCCESS;
    }
}
