<?php

declare(strict_types=1);

namespace apexl\Io\services;

use apexl\Io\includes\Entity;
use Arrayy\Type\StringCollection;

final readonly class LoaderDataFieldsResolver
{
    public function resolve(
        string $table,
        StringCollection $fields,
        Entity $entity,
        bool $autoIncludePrimaryKey = true
    ): StringCollection {
        if ($fields->contains('*')) {
            return $this->allFields($table, $entity);
        }

        $fields = $fields->filter($entity->isDataField(...))
            ->map(fn(string $field): string => $this->qualifyWithTable($field, $table));

        if ($autoIncludePrimaryKey) {
            $primaryKey = $this->qualifyWithTable($entity->getPrimaryKey(), $table);
            if (!$fields->contains($primaryKey)) {
                $fields->unshift($primaryKey);
            }
        }

        return $fields;
    }

    private function allFields(string $table, Entity $entity): StringCollection
    {
        $fields = array_map(
            fn(string $field) => $this->qualifyWithTable($field, $table),
            $entity->getEntityDataFieldNames(),

        );

        return StringCollection::createFromArray(array_values($fields));
    }

    private function qualifyWithTable(string $field, string $table): string
    {
        return sprintf('%s.%s', $table, $field);
    }
}