<?php

namespace App\Http\Controllers;

use App\Http\Requests\DealBuilderDeliveryRequest;
use App\Http\Resources\DealBuilderDeliveryListResource;
use App\Http\Resources\DealBuilderDeliveryViewResource;
use Mtc\MercuryDataModels\DealBuilder\DeliveryConfig;
use Mtc\MercuryDataModels\Dealership;

class DealBuilderDeliveryController extends Controller
{
    public function index(): DealBuilderDeliveryListResource
    {
        return new DealBuilderDeliveryListResource(
            Dealership::query()->with('dealBuilderDeliveryConfig.holidays')->get()
        );
    }

    public function show(Dealership $delivery): DealBuilderDeliveryViewResource
    {
        return new DealBuilderDeliveryViewResource($delivery);
    }

    public function update(
        DealBuilderDeliveryRequest $request,
        Dealership $delivery
    ): DealBuilderDeliveryViewResource {
        /** @var DeliveryConfig $config */
        $config = $delivery->dealBuilderDeliveryConfig()->firstOrNew([
            'dealership_id' => $delivery->id,
        ]);

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

        return new DealBuilderDeliveryViewResource($delivery);
    }
}
