<?php

declare(strict_types=1);

namespace App\Http\Api\Schema;

use App\Contracts\Http\Api\Field\FilterableField;
use App\Contracts\Http\Api\Field\SortableField;
use App\Contracts\Http\Api\Schema\SchemaInterface;
use App\Http\Api\Field\Base\CreatedAtField;
use App\Http\Api\Field\Base\DeletedAtField;
use App\Http\Api\Field\Base\UpdatedAtField;
use App\Http\Api\Field\Field;
use App\Http\Api\Filter\Filter;
use App\Http\Api\Filter\TrashedFilter;
use App\Http\Api\Include\AllowedInclude;
use App\Http\Api\Sort\RandomSort;
use App\Http\Api\Sort\Sort;
use Illuminate\Support\Arr;

abstract class Schema implements SchemaInterface
{
    /**
     * @return Field[]
     */
    public function fields(): array
    {
        return [
            new CreatedAtField($this),
            new UpdatedAtField($this),
            new DeletedAtField($this),
        ];
    }

    /**
     * @return Filter[]
     */
    public function filters(): array
    {
        return collect($this->fields())
            ->filter(fn (Field $field): bool => $field instanceof FilterableField)
            ->map(fn (FilterableField $field): Filter => $field->getFilter())
            ->push(new TrashedFilter())
            ->all();
    }

    /**
     * @return Sort[]
     */
    public function sorts(): array
    {
        return collect($this->fields())
            ->filter(fn (Field $field): bool => $field instanceof SortableField)
            ->map(fn (SortableField $field): Sort => $field->getSort())
            ->push(new RandomSort())
            ->all();
    }

    /**
     * Get the schema of the relation by path.
     */
    public function relation(string $path): ?Schema
    {
        $relationInclude = Arr::first($this->allowedIncludes(), fn (AllowedInclude $include): bool => $include->path() === $path);

        /** @phpstan-ignore-next-line */
        return $relationInclude?->schema();
    }

    /**
     * @return AllowedInclude[]
     */
    abstract public function allowedIncludes(): array;
}
