<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class SchedulingMode extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'competition_id',
        'name',
        'description',
        'algorithm',
        'config',
        'sequence_order',
        'status',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'config' => 'array',
    ];

    /**
     * Get the competition that this scheduling mode belongs to.
     */
    public function competition(): BelongsTo
    {
        return $this->belongsTo(Competition::class);
    }

    /**
     * Get the matches associated with this scheduling mode.
     */
    public function matches(): HasMany
    {
        return $this->hasMany(MatchGame::class);
    }

    /**
     * Get competitions that are currently using this scheduling mode.
     */
    public function activeCompetitions(): HasMany
    {
        return $this->hasMany(Competition::class, 'current_scheduling_mode_id');
    }

    /**
     * Check if this is the current active scheduling mode for its competition.
     *
     * @return bool
     */
    public function isActive(): bool
    {
        return $this->competition->current_scheduling_mode_id === $this->id;
    }

    /**
     * Generate match schedule based on the algorithm defined.
     *
     * @return array
     */
    public function generateSchedule(): array
    {
        // This would contain the logic to delegate to different scheduling algorithms
        // based on the 'algorithm' field
        switch ($this->algorithm) {
            case 'round_robin':
                return $this->generateRoundRobinSchedule();

            case 'knockout':
                return $this->generateKnockoutSchedule();

            case 'group_stage':
                return $this->generateGroupStageSchedule();

            default:
                return [];
        }
    }

    /**
     * Example implementation for round-robin scheduling.
     *
     * @return array
     */
    private function generateRoundRobinSchedule(): array
    {
        // Implementation would go here
        return [];
    }

    /**
     * Example implementation for knockout scheduling.
     *
     * @return array
     */
    private function generateKnockoutSchedule(): array
    {
        // Implementation would go here
        return [];
    }

    /**
     * Example implementation for group stage scheduling.
     *
     * @return array
     */
    private function generateGroupStageSchedule(): array
    {
        // Implementation would go here
        return [];
    }
}
