<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Concerns\ScopesApiToAccount;
use App\Services\Care\AppointmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class QueueController extends Controller
{
    use ScopesApiToAccount;

    public function __construct(
        protected AppointmentService $appointments,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorizeAbility($request, 'appointments.view');

        $validated = $request->validate([
            'branch_id' => ['required', 'integer', 'exists:care_branches,id'],
            'practitioner_id' => ['nullable', 'integer', 'exists:care_practitioners,id'],
        ]);

        $queue = $this->appointments->queue(
            $this->ownerRef($request),
            (int) $validated['branch_id'],
            isset($validated['practitioner_id']) ? (int) $validated['practitioner_id'] : null,
        );

        return response()->json(['data' => $queue]);
    }
}
