<?php

namespace App\Http\Controllers;

use App\Domain\Document\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DocumentController extends Controller
{
    public function show(Document $document): StreamedResponse
    {
        $this->authorize('documents.view');
        $this->ensureSameAcademy($document);

        return $this->streamFile($document, 'inline');
    }

    public function download(Document $document): StreamedResponse
    {
        $this->authorize('documents.view');
        $this->ensureSameAcademy($document);

        return $this->streamFile($document, 'attachment');
    }

    public function preview(Document $document): StreamedResponse
    {
        $this->authorize('documents.view');
        $this->ensureSameAcademy($document);

        return $this->streamFile($document, 'inline');
    }

    private function streamFile(Document $document, string $disposition): StreamedResponse
    {
        $disk = Storage::disk('local');

        abort_unless($disk->exists($document->file_path), 404);

        return $disk->download(
            $document->file_path,
            $document->original_filename,
            [
                'Content-Type' => $document->mime_type,
                'Content-Disposition' => "{$disposition}; filename=\"{$document->original_filename}\"",
            ]
        );
    }

    private function ensureSameAcademy(Document $document): void
    {
        abort_unless(
            $document->academy_id === app('current_academy')?->id,
            403
        );
    }
}
