<?php

namespace App\Modules\ServiceBooking\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\ServiceBooking\BookingRepository;
use App\Modules\ServiceBooking\Http\Requests\BookingListRequest;
use App\Modules\ServiceBooking\Http\Requests\CreateBookingRequest;
use App\Modules\ServiceBooking\Http\Requests\UpdateBookingRequest;
use App\Modules\ServiceBooking\Http\Requests\UpdateBookingStatusRequest;
use App\Modules\ServiceBooking\Http\Resources\ListServiceBookings;
use App\Modules\ServiceBooking\Http\Resources\ViewServiceBooking;
use Mtc\MercuryDataModels\Booking;
use Mtc\MercuryDataModels\BookingStatus;

class BookingController extends Controller
{
    public function index(BookingListRequest $request): ListServiceBookings
    {
        $bookings = Booking::query()
            ->with([
                'packages',
                'deliveryOption',
                'location',
            ])
            ->whereNotIn('status', [BookingStatus::DRAFT->value, BookingStatus::CANCELLED->value])
            ->when(
                $request->filled('customer_id'),
                fn($query) => $query->where('customer_id', $request->input('customer_id'))
            )
            ->latest()
            ->paginate();
        return new ListServiceBookings($bookings);
    }

    public function store(CreateBookingRequest $request, BookingRepository $repository): ViewServiceBooking
    {
        $booking = $repository->create($request);
        return new ViewServiceBooking($booking);
    }

    public function show(Booking $booking): ViewServiceBooking
    {
        return new ViewServiceBooking($booking);
    }

    public function update(
        UpdateBookingRequest $request,
        Booking $booking,
        BookingRepository $repository
    ): ViewServiceBooking {
        $repository->update($booking, $request);
        return new ViewServiceBooking($booking);
    }

    public function updateStatus(UpdateBookingStatusRequest $request, Booking $booking): ViewServiceBooking
    {
        $booking->setStatus($request->input('status'));
        return new ViewServiceBooking($booking);
    }

    public function destroy(Booking $booking, BookingRepository $repository): ViewServiceBooking
    {
        $repository->cancel($booking);
        return $this->show($booking);
    }
}
