<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreCustomerDocumentRequest;
use App\Http\Resources\CustomerDocumentResource;
use App\Models\Customer;
use App\Models\CustomerDocument;
use App\Models\User;
use App\Services\CustomerDocumentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;

class CustomerDocumentController extends Controller
{
    public function __construct(private CustomerDocumentService $documents) {}

    public function store(StoreCustomerDocumentRequest $request, Customer $customer): JsonResponse
    {
        $actor = $request->user();

        assert($actor instanceof User);

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

        assert($file instanceof UploadedFile);

        $document = $this->documents->store(
            $actor,
            $customer,
            $request->documentType(),
            $file,
        );

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

    public function file(Customer $customer, CustomerDocument $document): StreamedResponse|BinaryFileResponse
    {
        $this->ensureBelongsToCustomer($customer, $document);

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

    public function destroy(Customer $customer, CustomerDocument $document): Response
    {
        $this->ensureBelongsToCustomer($customer, $document);
        $this->documents->delete($document);

        return response()->noContent();
    }

    private function ensureBelongsToCustomer(Customer $customer, CustomerDocument $document): void
    {
        abort_unless($document->customer_id === $customer->id, 404);
    }
}
