<?php

namespace Functional\Tracking\Models;

use Functional\Programs\Models\Program;
use Functional\Routines\Models\Routine;
use Functional\Tracking\Database\Factories\WorkoutSessionFactory;
use Functional\Tracking\Enums\WorkoutSessionStatus;
use Functional\Tracking\Events\WorkoutCompleted;
use Functional\Users\Models\User;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Séance d'entraînement réalisée par un utilisateur (ad hoc, ou issue d'une routine/d'un programme).
 *
 * @property WorkoutSessionStatus $status
 */
#[UseFactory(WorkoutSessionFactory::class)]
class WorkoutSession extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id', 'routine_id', 'program_id', 'title', 'started_at', 'ended_at',
        'status', 'notes', 'total_volume',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'ended_at' => 'datetime',
        'status' => WorkoutSessionStatus::class,
        'total_volume' => 'decimal:2',
    ];

    /**
     * Émet WorkoutCompleted quand une séance passe à "completed"
     * (à la création directe en completed, ou lors d'un changement de statut).
     * C'est le déclencheur écouté par la couche streaks.
     */
    protected static function booted(): void
    {
        $fire = function (WorkoutSession $session) {
            if ($session->status === WorkoutSessionStatus::Completed) {
                WorkoutCompleted::dispatch($session);
            }
        };

        static::created($fire);
        static::updated(function (WorkoutSession $session) use ($fire) {
            if ($session->wasChanged('status')) {
                $fire($session);
            }
        });
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function routine(): BelongsTo
    {
        return $this->belongsTo(Routine::class);
    }

    public function program(): BelongsTo
    {
        return $this->belongsTo(Program::class);
    }

    public function setLogs(): HasMany
    {
        return $this->hasMany(SetLog::class);
    }
}
