<?php

namespace App\Http\Controllers\Athlete;

use App\Http\Controllers\Controller;
use App\Http\Requests\Athlete\SendCoachRequestRequest;
use App\Models\Coach;
use App\Models\CoachRequest;
use App\Services\Coach\CoachRequestService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

/**
 * نسخه به‌روزشده Phase 13 — نسخه Phase 10 را جایگزین کنید.
 * تغییر: eager-load شدن review در index().
 */
class CoachRequestController extends Controller
{
    public function __construct(private readonly CoachRequestService $requestService)
    {
    }

    public function store(SendCoachRequestRequest $request, Coach $coach): RedirectResponse
    {
        $athlete = $request->user()->athlete;

        $this->authorize('create', [CoachRequest::class, $athlete]);

        try {
            $this->requestService->sendRequest($athlete, $coach, $request->string('message')->toString() ?: null);
        } catch (\RuntimeException $e) {
            return back()->withErrors(['request' => $e->getMessage()]);
        }

        return back()->with('status', 'درخواست شما برای مربی ارسال شد.');
    }

    public function index(): View
    {
        $requests = auth()->user()->athlete->coachRequests()
            ->with(['coach.user', 'coach.bankAccount', 'payment', 'review'])
            ->latest()
            ->get();

        return view('athlete.requests.index', compact('requests'));
    }

    public function myCoaches(): View
    {
        $coaches = auth()->user()->athlete->activeCoaches()->with('user')->get();

        return view('athlete.coaches.index', compact('coaches'));
    }
}
