<?php

namespace App\Services;

use App\Enums\BookingDocumentType;
use App\Models\Booking;
use App\Models\BookingDocument;
use App\Models\User;
use App\Support\LocalMedia;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BookingDocumentService
{
    public function __construct(private LocalMedia $media) {}

    public function store(User $actor, Booking $booking, UploadedFile $file): BookingDocument
    {
        if ($booking->documents()->count() >= BookingDocumentType::MAX_PER_BOOKING) {
            throw ValidationException::withMessages([
                'file' => 'A booking can have at most '.BookingDocumentType::MAX_PER_BOOKING.' payment proof images.',
            ]);
        }

        $stored = $this->media->store('bookings/'.$booking->id, $file);

        return $booking->documents()->create([
            ...$stored,
            'type' => BookingDocumentType::PaymentProof,
            'uploaded_by' => $actor->id,
            'created_at' => now(),
        ]);
    }

    public function delete(BookingDocument $document): void
    {
        $this->media->delete($document->path);
        $document->delete();
    }

    public function response(BookingDocument $document): StreamedResponse|BinaryFileResponse
    {
        return $this->media->response($document->path, $document->original_name);
    }
}
