<?php

namespace App\Http\Controllers;

use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class WorkFileDownloadController extends Controller
{
    public function __invoke(Request $request, File $file): StreamedResponse|Response
    {
        $work = $file->work()->firstOrFail();

        if ($request->user()?->cannot('view', $work)) {
            abort(403);
        }

        if (! Storage::disk($file->disk)->exists($file->path)) {
            abort(404);
        }

        return Storage::disk($file->disk)->response(
            $file->path,
            $file->name,
            ['Content-Type' => $file->mime_type ?: 'application/octet-stream'],
        );
    }
}
