<?php

namespace App\Models\SelfPaced;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * TopicTimer Model
 *
 * Tracks elapsed seconds a Trainee has spent on each CourseTopic within an Enrollment.
 * Unique per (enrollment_id, topic_id).
 *
 * @property int $id
 * @property int $enrollment_id
 * @property int $user_id
 * @property int $topic_id
 * @property int $elapsed_seconds
 * @property \Illuminate\Support\Carbon|null $last_active_at
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class TopicTimer extends Model
{
    protected $table = 'self_paced_topic_timers';

    protected $fillable = [
        'enrollment_id',
        'user_id',
        'topic_id',
        'elapsed_seconds',
        'last_active_at',
    ];

    protected $casts = [
        'elapsed_seconds' => 'integer',
        'last_active_at'  => 'datetime',
        'created_at'      => 'datetime',
        'updated_at'      => 'datetime',
    ];

    protected $attributes = [
        'elapsed_seconds' => 0,
    ];

    // =========================================================================
    // RELATIONSHIPS
    // =========================================================================

    public function enrollment(): BelongsTo
    {
        return $this->belongsTo(Enrollment::class, 'enrollment_id');
    }

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

    public function topic(): BelongsTo
    {
        return $this->belongsTo(CourseTopic::class, 'topic_id');
    }

    // =========================================================================
    // QUERY SCOPES
    // =========================================================================

    public function scopeForEnrollment($query, int $enrollmentId)
    {
        return $query->where('enrollment_id', $enrollmentId);
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    /**
     * Get or create a timer record for a given enrollment + topic.
     */
    public static function getOrCreate(int $enrollmentId, int $userId, int $topicId): self
    {
        return static::firstOrCreate(
            ['enrollment_id' => $enrollmentId, 'topic_id' => $topicId],
            ['user_id' => $userId, 'elapsed_seconds' => 0]
        );
    }

    /**
     * Increment elapsed seconds and update last_active_at.
     */
    public function addSeconds(int $seconds): void
    {
        $this->increment('elapsed_seconds', $seconds);
        $this->update(['last_active_at' => now()]);
    }

    /**
     * Get elapsed time formatted as "Xh Ym" or "Ym Zs".
     */
    public function getFormattedElapsed(): string
    {
        $total = $this->elapsed_seconds;
        $hours = (int) floor($total / 3600);
        $minutes = (int) floor(($total % 3600) / 60);
        $seconds = $total % 60;

        if ($hours > 0) {
            return "{$hours}h {$minutes}m";
        }

        if ($minutes > 0) {
            return "{$minutes}m {$seconds}s";
        }

        return "{$seconds}s";
    }
}
