<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Member;
use App\Services\Care\CarePermissions;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

/**
 * Legacy Ladill Queue console routes — redirect each role to its natural
 * Care list (billing booth, pharmacy/lab queues, doctor patient-flow board).
 */
class ServiceQueueController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'service_queues.console');

        return $this->redirectAwayFromLegacyConsole($request);
    }

    public function console(Request $request, string $counterUuid): RedirectResponse
    {
        $this->authorizeAbility($request, 'service_queues.console');

        return $this->redirectAwayFromLegacyConsole($request);
    }

    public function action(Request $request, string $counterUuid): RedirectResponse
    {
        $this->authorizeAbility($request, 'service_queues.console');

        return $this->redirectAwayFromLegacyConsole($request);
    }

    protected function redirectAwayFromLegacyConsole(Request $request): RedirectResponse
    {
        $member = $this->member($request);
        $permissions = app(CarePermissions::class);

        if ($permissions->canAccessPatientQueue($member)) {
            return redirect()->route('care.queue.index');
        }

        return redirect()->route($this->naturalListRouteFor($member));
    }

    /**
     * Role pages that own Call next / payment ops after the old counter console
     * was removed. Must be a route the member can open (not appointments for
     * cashiers / pharmacists / lab techs who lack appointments.view).
     */
    protected function naturalListRouteFor(?Member $member): string
    {
        return match ($member?->role) {
            'cashier' => 'care.bills.index',
            'pharmacist' => 'care.prescriptions.queue',
            'lab_technician', 'lab_manager' => 'care.lab.queue.index',
            'blood_bank_manager' => 'care.blood-bank.admin.index',
            'receptionist', 'nurse' => 'care.appointments.index',
            default => 'care.dashboard',
        };
    }
}
