<?php

namespace App\Http\Controllers\Coach;

use App\Enums\CoachDocumentType;
use App\Http\Controllers\Controller;
use App\Http\Requests\Coach\UploadCoachDocumentRequest;
use App\Models\CoachDocument;
use App\Services\Coach\CoachProfileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DocumentController extends Controller
{
    public function __construct(private readonly CoachProfileService $profileService)
    {
    }

    public function store(UploadCoachDocumentRequest $request): RedirectResponse
    {
        $coach = $request->user()->coach;

        $this->authorize('upload', [CoachDocument::class, $coach]);

        try {
            $this->profileService->addDocument(
                $coach,
                $request->file('document'),
                CoachDocumentType::from($request->string('type')->toString()),
                $request->user()->id,
            );
        } catch (\RuntimeException $e) {
            return back()->withErrors(['document' => $e->getMessage()]);
        }

        return back()->with('status', 'مدرک با موفقیت آپلود شد.');
    }

    public function destroy(CoachDocument $document): RedirectResponse
    {
        $this->authorize('delete', $document);

        $this->profileService->deleteDocument($document);

        return back()->with('status', 'مدرک حذف شد.');
    }

    /**
     * سرو امن فایل خصوصی — هرگز مستقیم از طریق URL storage قابل دسترسی نیست،
     * فقط از این Route که Policy را چک می‌کند (طبق بند ۳۹: Authorization برای مشاهده مدارک).
     */
    public function show(CoachDocument $document): StreamedResponse
    {
        $this->authorize('view', $document);

        return Storage::disk('local_private')->response(
            $document->stored_path,
            $document->original_name,
            ['Content-Type' => $document->mime_type]
        );
    }
}
