<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreBookingDocumentRequest;
use App\Http\Resources\BookingDocumentResource;
use App\Models\Booking;
use App\Models\BookingDocument;
use App\Models\User;
use App\Services\BookingDocumentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BookingDocumentController extends Controller
{
    public function __construct(private BookingDocumentService $documents) {}

    public function store(StoreBookingDocumentRequest $request, Booking $booking): JsonResponse
    {
        $actor = $request->user();

        assert($actor instanceof User);

        $file = $request->file('file');

        assert($file instanceof UploadedFile);

        $document = $this->documents->store($actor, $booking, $file);

        return BookingDocumentResource::make($document)
            ->response()
            ->setStatusCode(201);
    }

    public function file(Booking $booking, BookingDocument $document): StreamedResponse|BinaryFileResponse
    {
        $this->ensureBelongsToBooking($booking, $document);

        return $this->documents->response($document);
    }

    public function destroy(Booking $booking, BookingDocument $document): Response
    {
        $this->ensureBelongsToBooking($booking, $document);
        $this->documents->delete($document);

        return response()->noContent();
    }

    private function ensureBelongsToBooking(Booking $booking, BookingDocument $document): void
    {
        abort_unless($document->booking_id === $booking->id, 404);
    }
}
