<?php

declare(strict_types=1);

namespace App\GraphQL\Schema\Fields\Wiki\Anime\AnimeYear\AnimeYearSeason;

use App\Actions\GraphQL\IndexAction;
use App\Contracts\GraphQL\Fields\DisplayableField;
use App\GraphQL\Argument\Argument;
use App\GraphQL\Schema\Fields\Field;
use App\GraphQL\Schema\Queries\Models\Pagination\Wiki\AnimePaginationQuery;
use App\GraphQL\Schema\Types\Wiki\AnimeType;
use App\Models\Wiki\Anime;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Rebing\GraphQL\Support\Facades\GraphQL;

class AnimeYearSeasonAnimeField extends Field implements DisplayableField
{
    final public const string FIELD = 'anime';

    public function __construct()
    {
        parent::__construct(self::FIELD, nullable: false);
    }

    public function description(): string
    {
        return 'The animes of the season year filtered';
    }

    public function baseType(): AnimeType
    {
        return new AnimeType();
    }

    public function type(): Type
    {
        return Type::nonNull(GraphQL::paginate($this->baseType()->name()));
    }

    public function canBeDisplayed(): bool
    {
        return true;
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    public function args(): array
    {
        return collect(new AnimePaginationQuery()->arguments())
            ->mapWithKeys(fn (Argument $argument): array => [
                $argument->getName() => [
                    'name' => $argument->getName(),
                    'type' => $argument->getType(),

                    ...(is_null($argument->getDefaultValue()) ? [] : ['defaultValue' => $argument->getDefaultValue()]),
                ],
            ])
            ->all();
    }

    /**
     * Get the arguments of the field.
     *
     * @return Argument[]
     */
    public function arguments(): array
    {
        return new AnimePaginationQuery()->arguments();
    }

    /**
     * @return Paginator
     */
    public function resolve($root, array $args, $context, ResolveInfo $resolveInfo): mixed
    {
        $season = Arr::get($root, AnimeYearSeasonSeasonField::FIELD);
        $year = Arr::get($root, 'year');

        $builder = Anime::query()
            // season filter applies only on the 'season' field.
            ->when($season !== null, fn (Builder $query) => $query->where(Anime::ATTRIBUTE_SEASON, $season->value))
            ->where(Anime::ATTRIBUTE_YEAR, $year);

        return new IndexAction()->index($builder, $args, new AnimeType(), $resolveInfo);
    }
}
