<?php

namespace App\Domain\Training\Models;

use App\Domain\Facility\Models\Facility;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Training\Enums\SessionStatus;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Domain\Shared\Traits\BelongsToBranch;

class TrainingSession extends Model
{
    use BelongsToAcademy, HasUuid, Auditable, BelongsToBranch;

    protected $fillable = [
        'academy_id', 'branch_id', 'training_group_id', 'schedule_id', 'facility_id',
        'session_date', 'start_time', 'end_time',
        'trainer_id', 'assistant_trainer_id', 'substitute_reason',
        'session_number', 'topic', 'objectives',
        'status', 'cancelled_reason', 'cancelled_by', 'rescheduled_to_id',
        'weather_condition', 'actual_start_time', 'actual_end_time',
        'expected_participants', 'actual_participants',
        'notes', 'incident_notes', 'equipment_used', 'metadata',
    ];

    protected $casts = [
        'status' => SessionStatus::class,
        'session_date' => 'date',
        'session_number' => 'integer',
        'expected_participants' => 'integer',
        'actual_participants' => 'integer',
        'equipment_used' => 'array',
        'metadata' => 'array',
    ];

    public function group(): BelongsTo
    {
        return $this->belongsTo(TrainingGroup::class, 'training_group_id');
    }

    public function schedule(): BelongsTo
    {
        return $this->belongsTo(TrainingSchedule::class, 'schedule_id');
    }

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

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

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

    public function rescheduledTo(): BelongsTo
    {
        return $this->belongsTo(self::class, 'rescheduled_to_id');
    }

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

    public function attendanceRecords(): HasMany
    {
        return $this->hasMany(\App\Domain\Attendance\Models\AttendanceRecord::class, 'training_session_id');
    }

    public function scopeUpcoming($query)
    {
        return $query->where('session_date', '>=', now()->toDateString())
            ->where('status', SessionStatus::Scheduled);
    }

    public function scopeForDate($query, $date)
    {
        return $query->where('session_date', $date);
    }
}
