<?php

namespace App\Domain\Training\Models;

use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Training\Enums\GroupStatus;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class TrainingGroup extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable;

    protected $fillable = [
        'academy_id', 'training_program_id', 'branch_id',
        'name', 'name_ar', 'code',
        'head_trainer_id', 'max_capacity', 'current_count', 'waitlist_count',
        'season', 'start_date', 'end_date',
        'status', 'status_changed_at', 'notes', 'metadata', 'created_by',
    ];

    protected $casts = [
        'status' => GroupStatus::class,
        'max_capacity' => 'integer',
        'current_count' => 'integer',
        'waitlist_count' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
        'status_changed_at' => 'datetime',
        'metadata' => 'array',
    ];

    public function program(): BelongsTo
    {
        return $this->belongsTo(TrainingProgram::class, 'training_program_id');
    }

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

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

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

    public function schedules(): HasMany
    {
        return $this->hasMany(TrainingSchedule::class, 'training_group_id');
    }

    public function sessions(): HasMany
    {
        return $this->hasMany(TrainingSession::class, 'training_group_id');
    }

    public function enrollments(): HasMany
    {
        return $this->hasMany(Enrollment::class, 'training_group_id');
    }

    public function waitlists(): HasMany
    {
        return $this->hasMany(Waitlist::class, 'training_group_id');
    }

    public function isFull(): bool
    {
        return $this->current_count >= $this->max_capacity;
    }

    public function hasAvailableSpots(): bool
    {
        return $this->current_count < $this->max_capacity;
    }

    public function scopeActive($query)
    {
        return $query->where('status', GroupStatus::Active);
    }

    public function scopeAcceptingEnrollments($query)
    {
        return $query->whereIn('status', [GroupStatus::Active->value, GroupStatus::Forming->value]);
    }
}
