<?php

/** @noinspection PhpDocSignatureIsNotCompleteInspection */

namespace DefStudio\GameEngine\Actions\Awards;

use DefStudio\Actions\Action;
use DefStudio\GameEngine\Models\Award;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
use DefStudio\GameEngine\Models\Contracts\FitsInScope;
use DefStudio\GameEngine\Models\Contracts\AwardsDefiner;

/**
 * @method static Collection<int, Award> run(Model|null $model)
 */
class GetAwardsForScope extends Action
{
    /**
     * @return Collection<int, Award>
     */
    public function handle(Model|null $model): Collection
    {
        if ($model === null) {
            return Collection::empty();
        }

        $awards = Collection::empty();

        if ($model instanceof AwardsDefiner) {
            $awards->push(...$model->awards->whereNull('parent_id')->sortByDesc('order'));
        }

        if ($model instanceof FitsInScope) {
            $model->traverse_parent_scopes(function(Model $parent) use ($awards): void {
                if ($parent instanceof AwardsDefiner) {
                    $awards->push(...$parent->awards->whereNull('parent_id')->sortByDesc('order'));
                }
            });
        }

        $awards->push(...game_engine()->awardQuery()->whereNull('scope_id')->whereNull('parent_id')->orderBy('order', 'desc')->get());

        /** @var Collection<int, Award> $awards */
        $awards = Collection::make([...$awards->reverse()->values()]);

        return $awards;
    }
}
