<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\Download;
use App\Models\Page;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DownloadsController extends Controller
{
    public function index(): View
    {
        $page = Page::query()
            ->published()
            ->where('route_path', '/downloads')
            ->with('sections')
            ->first();

        $downloads = Download::query()->published()->orderBy('sort_order')->get();

        return view('site.downloads', compact('page', 'downloads'));
    }

    public function file(Download $download): StreamedResponse|Response
    {
        abort_unless($download->is_published, 404);

        $media = $download->media;

        return Storage::disk($media->disk)->download($media->path, $media->filename);
    }
}
