<?php

namespace App\Services;

use App\Enums\CustomerDocumentType;
use App\Models\Customer;
use App\Models\CustomerDocument;
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 CustomerDocumentService
{
    public function __construct(private LocalMedia $media) {}

    public function store(User $actor, Customer $customer, CustomerDocumentType $type, UploadedFile $file): CustomerDocument
    {
        if ($customer->documents()->count() >= CustomerDocumentType::MAX_PER_CUSTOMER) {
            throw ValidationException::withMessages([
                'file' => 'A customer can have at most '.CustomerDocumentType::MAX_PER_CUSTOMER.' images.',
            ]);
        }

        $typeCount = $customer->documents()->where('type', $type)->count();

        if ($typeCount >= $type->maxPerCustomer()) {
            throw ValidationException::withMessages([
                'type' => 'Only '.$type->maxPerCustomer().' '.$type->label().' image(s) can be uploaded.',
            ]);
        }

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

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

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

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