<?php

namespace App\Http\Controllers\Api\V1\Documents;

use App\Domain\Documents\Models\Document;
use App\Domain\Documents\Services\DocumentService;
use App\Domain\Documents\Services\DocumentStorage;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Streams a document to an authorized reader (§17B.6, §17B.15).
 *
 * The storage path never leaves the server: callers get either a short-lived
 * signed URL from the driver, or a streamed response. Every access is logged.
 */
class DocumentDownloadController extends Controller
{
    public function __construct(
        private readonly DocumentStorage $storage,
        private readonly DocumentService $documents,
    ) {}

    public function __invoke(Request $request, Document $document): Response
    {
        $this->authorize('download', $document);

        if (blank($document->file_path) || ! $this->storage->exists($document)) {
            return ApiResponse::error('The stored file is no longer available.', [], 404);
        }

        $this->documents->logAccess(
            $document,
            $request->user(),
            $request->boolean('preview') ? 'preview' : 'download',
            $request->ip(),
            $request->userAgent(),
        );

        $signed = $this->storage->temporaryUrl($document);

        if ($signed !== null) {
            return ApiResponse::success(['url' => $signed, 'expires_in_minutes' => config('mams.documents.link_ttl_minutes')]);
        }

        // Local disk: stream it, inline for preview and as an attachment otherwise.
        return $this->storage->disk()->response(
            $document->file_path,
            $document->original_name,
            ['Content-Type' => $document->mime_type],
            $request->boolean('preview') ? 'inline' : 'attachment',
        );
    }
}
