<?php

declare(strict_types=1);

namespace App\Http\Controllers\Internal;

use App\Http\Controllers\Controller;
use App\Models\EnhanceJob;
use App\Services\Enhance\EnhanceStorageService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Throwable;

final class EnhanceSourceController extends Controller
{
    public function __construct(
        private readonly EnhanceStorageService $storage,
    ) {
    }

    public function show(Request $request, EnhanceJob $enhanceJob): Response
    {
        abort_unless($request->hasValidSignature(), 403);
        abort_unless($this->storage->isEnhancePath($enhanceJob->source_path), 404);

        try {
            $binary = $this->storage->fetchSourceBinary($enhanceJob);
        } catch (Throwable) {
            abort(404);
        }

        return response($binary, 200, [
            'Content-Type' => trim((string) ($enhanceJob->input_mime ?: 'application/octet-stream')),
            'Content-Length' => (string) strlen($binary),
            'Cache-Control' => 'private, max-age=60',
            'Content-Disposition' => 'inline; filename="enhance-source-' . $enhanceJob->id . '"',
        ]);
    }
}