<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Booking\SlotEngine;
use App\Http\Controllers\Controller;
use App\Models\Dentist;
use App\Support\ClinicTime;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;

class AvailabilityController extends Controller
{
    public function __invoke(Request $request, SlotEngine $engine)
    {
        $request->validate([
            'dentist_id' => ['required', 'integer'],
            'date' => ['required', 'date_format:Y-m-d'],
        ]);

        $dentist = Dentist::findOrFail($request->dentist_id);

        $slots = $engine->availableSlots(
            $dentist,
            CarbonImmutable::parse($request->date, ClinicTime::timezone()),
        );

        return response()->json([
            'data' => $slots->map(fn ($s) => [
                'label' => $s['label'],
                'starts_at_local' => $s['starts_at_utc']->setTimezone(ClinicTime::timezone())->format('Y-m-d H:i'),
            ])->all(),
        ]);
    }
}
