<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreReservePrice;
use App\Http\Requests\UpdateReservationPrice;
use App\Http\Resources\ReservationPriceResource;
use Illuminate\Http\Response;
use Mtc\MercuryDataModels\ReservationPrice;

class ReservationPriceController extends Controller
{
    public function index()
    {
        return ReservationPrice::query()->with('rules')->paginate()
            ->through(function ($price) {
                $price->rule_description = $price->rules
                    ->map(fn($rule) => $rule->field_name . ' ' . $rule->condition_name . ' ' . $rule->value_name)
                    ->implode(', ');
                return $price;
            });
    }

    public function store(StoreReservePrice $request): ReservationPriceResource
    {
        return new ReservationPriceResource(ReservationPrice::query()
            ->create([
                'price' => $request->input('price'),
                'label' => $request->input('label'),
            ]));
    }

    public function show(ReservationPrice $reservationPrice): ReservationPriceResource
    {
        return new ReservationPriceResource($reservationPrice);
    }

    public function update(
        UpdateReservationPrice $request,
        ReservationPrice $reservationPrice,
    ): ReservationPriceResource {

        $reservationPrice->update($request->input());
        $rules = collect($request->input('rules', []));

        // Remove rules not in list
        $reservationPrice->rules()
            ->whereNotIn('id', $rules->pluck('id'))
            ->delete();

        // Add/Update rules
        $rules->each(fn($rule) => $reservationPrice->rules()->updateOrCreate([ 'id' => $rule['id'] ], $rule));
        return new ReservationPriceResource($reservationPrice);
    }

    public function destroy(ReservationPrice $price): Response
    {
        $price->delete();
        return response('ok');
    }
}
