<?php

namespace App\Http\Controllers\Athlete;

use App\Enums\BodyPhotoAngle;
use App\Http\Controllers\Controller;
use App\Http\Requests\Athlete\UploadBodyPhotoRequest;
use App\Models\AthleteAssessment;
use App\Models\BodyPhoto;
use App\Services\Athlete\AssessmentService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;

class BodyPhotoController extends Controller
{
    public function __construct(private readonly AssessmentService $assessmentService)
    {
    }

    public function store(UploadBodyPhotoRequest $request, AthleteAssessment $assessment): RedirectResponse
    {
        $this->authorize('uploadPhoto', $assessment);

        try {
            $this->assessmentService->addPhoto(
                $assessment,
                $request->file('photo'),
                BodyPhotoAngle::from($request->string('angle')->toString()),
                $request->user()->id,
            );
        } catch (\RuntimeException $e) {
            return back()->withErrors(['photo' => $e->getMessage()]);
        }

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

    /**
     * سرو امن — طبق بند ۱۰/۳۹، تصاویر بدن هرگز public نیستند.
     * Authorization از طریق assessment->athlete (همان AthleteAssessmentPolicy) چک می‌شود.
     */
    public function show(BodyPhoto $photo): StreamedResponse
    {
        $this->authorize('view', $photo->assessment);

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

    // عمداً متد destroy وجود ندارد — طبق بند ۱۲، تصاویر ارزیابی هرگز از UI کاربر حذف نمی‌شوند.
}
