<?php

namespace App\Http\Controllers;

use App\Models\Document;
use App\Services\DocumentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DocumentController extends Controller
{
    public function __construct(
        private DocumentService $documentService
    ) {}

    public function store(Request $request)
    {
        $validated = $request->validate([
            'titel'      => 'required|string|max:255',
            'bestand'    => 'required|file|max:20480',
            'project_id' => 'required|exists:projects,id',
            'fase_id'    => 'nullable|exists:fases,id',
            'type'       => 'nullable|string|max:50',
        ]);

        $this->documentService->upload($validated, $request->file('bestand'));

        return back()->with('success', 'Document geupload.');
    }

    public function download(Document $document)
    {
        abort_unless(
            Storage::disk('local')->exists($document->bestandspad),
            404,
            'Bestand niet gevonden.'
        );

        return Storage::disk('local')->download(
            $document->bestandspad,
            $document->titel
        );
    }

    public function destroy(Document $document)
    {
        $this->documentService->delete($document);

        return back()->with('success', 'Document verwijderd.');
    }
}
