<?php

namespace App\Http\Controllers\Coach;

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

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

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

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

        return back()->with('status', 'حرکت اضافه شد.');
    }

    public function update(WorkoutExerciseRequest $request, WorkoutExercise $exercise): RedirectResponse
    {
        $this->authorize('update', $exercise->session->plan);

        $this->builder->updateExercise($exercise, $request->validated());

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

    public function duplicate(WorkoutExercise $exercise): RedirectResponse
    {
        $this->authorize('update', $exercise->session->plan);

        $this->builder->duplicateExercise($exercise);

        return back()->with('status', 'حرکت کپی شد.');
    }

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

        $this->builder->deleteExercise($exercise);

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

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

        $this->builder->reorderExercises($session, $request->input('ordered_ids'));

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