<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateReservationRequest;
use App\Http\Resources\ReservationList;
use App\Http\Resources\ReservationView;
use Illuminate\Http\Request;
use Mtc\VehicleReservations\Reservation;
use Mtc\VehicleReservations\ReservationRepository;

class ReservationController extends Controller
{
    public function index(Request $request)
    {
        return new ReservationList(
            Reservation::query()
                ->with('vehicle', fn ($query) => $query->withTrashed())
                ->whereNotNull('confirmed_at')
                ->when(
                    $request->filled('customer_id'),
                    fn($query) => $query->where('customer_id', $request->input('customer_id'))
                )
                ->latest()
                ->paginate()
        );
    }

    public function show(Reservation $reservation)
    {
        return new ReservationView($reservation);
    }

    public function update(UpdateReservationRequest $request, Reservation $reservation): ReservationView
    {
        $reservation->update($request->validated());
        return new ReservationView($reservation);
    }

    public function destroy(Reservation $reservation): ReservationList
    {
        $reservation->update(['status' => 'cancelled']);

        $vehicleHasNoReservation = $reservation->vehicle->reservations()
            ->whereNotIn('status', ['pending', 'cancelled'])
            ->exists();
        if ($vehicleHasNoReservation) {
            $reservation->vehicle->update(['is_reserved' => false]);
        }

        return $this->index($reservation);
    }
}
