<?php

declare(strict_types=1);

namespace App\GraphQL\Filter;

use BackedEnum;
use Closure;
use Illuminate\Support\Arr;
use UnitEnum;

class EnumFilter extends Filter
{
    /**
     * @param  class-string<UnitEnum>  $enumClass
     */
    public function __construct(
        protected string $enumName,
        protected readonly string $enumClass,
        string $column,
    ) {
        parent::__construct($enumName, $column);
    }

    /**
     * Convert filter values if needed. By default, no conversion is needed.
     */
    protected function convertFilterValues(array $filterValues): array
    {
        $values = [];

        foreach ($filterValues as $filterValue) {
            if ($filterValue instanceof BackedEnum) {
                $values[] = $filterValue->value;
                continue;
            }

            /** @var BackedEnum $enum */
            $enum = Arr::first(
                $this->enumClass::cases(),
                fn (UnitEnum $enum): bool => $enum->name === $filterValue
            );

            $values[] = $enum->value;
        }

        return $values;
    }

    /**
     * Get the validation rules for the filter.
     */
    protected function getRules(): array
    {
        return [
            'required',
            function ($attribute, mixed $value, Closure $fail): void {
                if (
                    Arr::first($this->enumClass::cases(), fn (UnitEnum $enum): bool => $enum->name === $value) === null
                    && ! $value instanceof BackedEnum
                ) {
                    $fail("'{$value}' does not exist in the ".class_basename($this->enumClass).' enum.');
                }
            },
        ];
    }
}
