<?php

namespace App\Services\Care;

use App\Models\Appointment;
use App\Models\Consultation;
use App\Services\Care\CareQueueContexts;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\RedirectResponse;

class CareQueueSessionAdvance
{
    public function __construct(
        protected CareQueueBridge $queueBridge,
        protected ConsultationService $consultations,
        protected AppointmentService $appointments,
    ) {}

    /**
     * End the current encounter so Call next can open the following patient.
     */
    public function endCurrentEncounter(Appointment $appointment, string $ownerRef, ?string $actorRef = null): void
    {
        $appointment->loadMissing(['consultation', 'organization']);

        $consultation = $appointment->consultation;
        if ($consultation && $consultation->status !== Consultation::STATUS_COMPLETED) {
            $this->consultations->complete($consultation, $ownerRef, $actorRef);

            return;
        }

        if ($appointment->status === Appointment::STATUS_IN_CONSULTATION) {
            $this->appointments->complete($appointment, $ownerRef, $actorRef);

            return;
        }

        if ($appointment->organization && in_array($appointment->queue_ticket_status, ['called', 'serving'], true)) {
            $this->queueBridge->complete($appointment->organization, $appointment);
        }
    }

    /**
     * Open the patient who was just called — without starting the session.
     * Specialty → workspace overview; GP → appointment (Start + Call again).
     */
    public function redirectToOpenedPatient(
        Appointment|Model|null $entity,
        array $ticket,
        string $fallbackRoute = 'care.queue.index',
        array $fallbackParams = [],
    ): RedirectResponse {
        $message = 'Called '.($ticket['ticket_number'] ?? 'next').' — '.($ticket['customer_name'] ?? 'patient').'.';

        if (! $entity instanceof Appointment) {
            return redirect()->route($fallbackRoute, $fallbackParams)->with('success', $message);
        }

        $entity->loadMissing(['visit', 'organization', 'department']);
        $organization = $entity->organization;
        if (! $organization) {
            return redirect()->route($fallbackRoute, $fallbackParams)->with('success', $message);
        }

        $context = $this->queueBridge->contextForAppointment($organization, $entity);

        if ($context !== CareQueueContexts::CONSULTATION && $entity->visit) {
            return redirect()
                ->route('care.specialty.workspace', [
                    'module' => $context,
                    'visit' => $entity->visit,
                    'tab' => 'overview',
                ])
                ->with('success', $message);
        }

        return redirect()
            ->route('care.appointments.show', $entity)
            ->with('success', $message);
    }
}
