<?php

namespace App\Modules\ServiceBooking\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\ServiceAvailabilityRequest;
use App\Http\Resources\ServiceAvailabilityList;
use App\Http\Resources\ServiceAvailabilityView;
use Mtc\MercuryDataModels\BookingAvailability;
use Mtc\MercuryDataModels\Dealership;

class ServiceAvailabilityController extends Controller
{
    public function index(): ServiceAvailabilityList
    {
        return new ServiceAvailabilityList(Dealership::query()->with('serviceAvailability.holidays')->get());
    }

    public function show(Dealership $availability): ServiceAvailabilityView
    {
        return new ServiceAvailabilityView($availability);
    }

    public function update(ServiceAvailabilityRequest $request, Dealership $availability): ServiceAvailabilityView
    {
        /** @var BookingAvailability $serviceAvailability */
        $serviceAvailability = $availability->serviceAvailability()->firstOrNew([
            'dealership_id' => $availability->id,
        ]);

        $serviceAvailability->fill($request->validated())->save();
        $serviceAvailability->allocateHolidays($request->input('holidays', []));

        return new ServiceAvailabilityView($availability);
    }

    public function delete(Dealership $availability): ServiceAvailabilityList
    {
        $availability->serviceAvailability()->delete();
        return $this->index();
    }
}
