<?php

namespace Functional\Tracking\Http\Resources;

use Functional\Exercises\Models\Exercise;
use Functional\Routines\Models\RoutineExercise;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * Une séance d'entraînement, avec ses séries (setLogs) quand elles sont chargées, et — pour une
 * séance issue d'une routine — les exercices planifiés (prêts-à-logger, avec séries/reps cibles).
 */
class WorkoutSessionResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'routine_id' => $this->routine_id,
            'status' => $this->status->value,
            'started_at' => $this->started_at,
            'ended_at' => $this->ended_at,
            'total_volume' => $this->total_volume,
            'notes' => $this->notes,
            'set_count' => $this->when($this->set_logs_count !== null, $this->set_logs_count),
            'set_logs' => SetLogResource::collection($this->whenLoaded('setLogs')),
            'planned_exercises' => $this->plannedExercises($request),
        ];
    }

    /**
     * Exercices prévus par la routine (dans l'ordre), pour pré-remplir la séance dès son démarrage.
     * Vide pour une séance ad hoc (sans routine).
     */
    private function plannedExercises(Request $request): array
    {
        if (! $this->relationLoaded('routine') || $this->routine === null) {
            return [];
        }

        $locale = (string) ($request->query('locale') ?: 'fr');

        return $this->routine->routineExercises
            ->map(function (RoutineExercise $routineExercise) use ($locale) {
                $exercise = $routineExercise->exercise;

                return [
                    'exercise_id' => $routineExercise->exercise_id,
                    'position' => $routineExercise->position,
                    'sets' => $routineExercise->sets,
                    'target_reps' => $routineExercise->target_reps,
                    'target_weight' => $routineExercise->target_weight,
                    'rest_seconds' => $routineExercise->rest_seconds,
                    'exercise' => $exercise ? [
                        'id' => $exercise->id,
                        'name' => $exercise->localizedName($locale),
                        'image_url' => $exercise->image_url,
                        'target' => Exercise::localizeTerm($exercise->target, $locale),
                    ] : null,
                ];
            })
            ->values()
            ->all();
    }
}
