<?php

namespace App\Http\Controllers;

use App\Http\Requests\DealBuilderPickupRequest;
use App\Http\Resources\DealBuilderPickupListResource;
use App\Http\Resources\DealBuilderPickupViewResource;
use Mtc\MercuryDataModels\DealBuilder\PickupAvailability;
use Mtc\MercuryDataModels\Dealership;

class DealBuilderPickupController extends Controller
{
    public function index(): DealBuilderPickupListResource
    {
        return new DealBuilderPickupListResource(
            Dealership::query()->with('dealBuilderPickupAvailability.holidays')->get()
        );
    }

    public function show(Dealership $pickup): DealBuilderPickupViewResource
    {
        return new DealBuilderPickupViewResource($pickup);
    }

    public function update(DealBuilderPickupRequest $request, Dealership $pickup): DealBuilderPickupViewResource
    {
        /** @var PickupAvailability $availability */
        $availability = $pickup->dealBuilderPickupAvailability()->firstOrNew([
            'dealership_id' => $pickup->id,
        ]);

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

        return new DealBuilderPickupViewResource($pickup);
    }
}
