<?php

declare(strict_types=1);

namespace Apexl\Io\Tabulator\Tabulatable\LoaderConditionCallback;

use Apexl\Io\Collections\LoaderConditionCollection;
use Apexl\Io\Dtos\LoaderCondition;
use Apexl\Io\Interfaces\LoaderConditionInterface;
use Apexl\Io\Tabulator\Dtos\TabulatorFilter;
use Apexl\Io\Tabulator\Interfaces\TabulatableLoaderConditionCallback;
use Apexl\Vault\Enums\WhereType;

final readonly class Truthy implements TabulatableLoaderConditionCallback
{
    public function __invoke(
        TabulatorFilter $filter,
    ): LoaderConditionInterface {

        if ($filter->value === false) {
            // Falsey means null OR false. The or() markers on the conditions are not
            // enough: LoaderConditionCollection::normaliseConditionType() overwrites
            // each child's type with the collection's, which defaults to AND — and
            // `IS NULL AND = false` can never match.
            return LoaderConditionCollection::createFromArray([
                LoaderCondition::or(LoaderCondition::isNull($filter->field)),
                LoaderCondition::or(LoaderCondition::equals($filter->field, false)),
            ])->setType(WhereType::OR);
        }

        return LoaderConditionCollection::createFromArray([
            LoaderCondition::notIn($filter->field, [true, '1']),
            LoaderCondition::notNull($filter->field),
        ]);
    }
}
