<?php

namespace Functional\Routines\Services;

use Functional\Routines\Models\Routine;
use Functional\Users\Models\User;
use Illuminate\Support\Str;

/**
 * Création/mise à jour d'une routine et synchronisation de son pivot routine_exercises.
 */
class RoutineService
{
    /** Champs propres à la routine (les exercices sont synchronisés à part). */
    private const ROUTINE_FIELDS = ['name', 'description', 'is_public', 'estimated_minutes'];

    public function create(User $user, array $data): Routine
    {
        $routine = new Routine($this->routineAttributes($data));
        $routine->user_id = $user->id;
        $routine->slug = Str::slug($data['name']);
        $routine->save();

        $this->syncExercises($routine, $data['exercises'] ?? []);

        return $routine->load('routineExercises.exercise');
    }

    public function update(Routine $routine, array $data): Routine
    {
        $routine->fill($this->routineAttributes($data));

        if (array_key_exists('name', $data)) {
            $routine->slug = Str::slug($data['name']);
        }

        $routine->save();

        if (array_key_exists('exercises', $data)) {
            $this->syncExercises($routine, $data['exercises']);
        }

        return $routine->load('routineExercises.exercise');
    }

    private function routineAttributes(array $data): array
    {
        return array_intersect_key($data, array_flip(self::ROUTINE_FIELDS));
    }

    /** Remplace intégralement le pivot par la liste fournie (stratégie simple : purge puis recrée, dans l'ordre donné). */
    private function syncExercises(Routine $routine, array $exercises): void
    {
        $routine->routineExercises()->delete();

        foreach ($exercises as $index => $exercise) {
            $routine->routineExercises()->create([
                'exercise_id' => $exercise['exercise_id'],
                'position' => $exercise['position'] ?? $index,
                'sets' => $exercise['sets'],
                'target_reps' => $exercise['target_reps'],
                'rest_seconds' => $exercise['rest_seconds'] ?? null,
                'tempo' => $exercise['tempo'] ?? null,
                'target_weight' => $exercise['target_weight'] ?? null,
                'notes' => $exercise['notes'] ?? null,
            ]);
        }
    }
}
