<?php

namespace App\Http\Controllers\Coach;

use App\Http\Controllers\Controller;
use App\Http\Requests\Coach\ReorderRequest;
use App\Http\Requests\Coach\WorkoutSessionRequest;
use App\Models\WorkoutPlan;
use App\Models\WorkoutSession;
use App\Services\Coach\WorkoutBuilderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;

class WorkoutSessionController extends Controller
{
    public function __construct(private readonly WorkoutBuilderService $builder)
    {
    }

    public function store(WorkoutSessionRequest $request, WorkoutPlan $plan): RedirectResponse
    {
        $this->authorize('update', $plan);

        $this->builder->addSession($plan, $request->string('title')->toString());

        return back()->with('status', 'جلسه جدید اضافه شد.');
    }

    public function update(WorkoutSessionRequest $request, WorkoutSession $session): RedirectResponse
    {
        $this->authorize('update', $session->plan);

        $this->builder->updateSession($session, $request->validated());

        return back()->with('status', 'جلسه به‌روزرسانی شد.');
    }

    public function destroy(WorkoutSession $session): RedirectResponse
    {
        $this->authorize('update', $session->plan);

        $this->builder->deleteSession($session);

        return back()->with('status', 'جلسه حذف شد.');
    }

    public function reorder(ReorderRequest $request, WorkoutPlan $plan): JsonResponse
    {
        $this->authorize('update', $plan);

        $this->builder->reorderSessions($plan, $request->input('ordered_ids'));

        return response()->json(['status' => 'ok']);
    }
}
