<?php

namespace Ulmus;

use Ulmus\Annotation\Property\{Field,
    OrderBy,
    Where,
    Having,
    Relation,
    Filter,
    Join,
    FilterJoin,
    WithJoin,
    Relation\Ignore as RelationIgnore};
use Ulmus\Common\EntityResolver;
use Ulmus\Repository\WithOptionEnum;

class Repository
{
    use EventTrait, Repository\ConditionTrait, Repository\EscapeTrait;

    const DEFAULT_ALIAS = "this";

    public ? ConnectionAdapter $adapter;

    public string $alias;

    public string $entityClass;

    public array $events = [];

    protected Query\QueryBuilderInterface $queryBuilder;

    protected EntityResolver $entityResolver;

    protected array $joined = [];

    public function __construct(string $entity, string $alias = self::DEFAULT_ALIAS, ConnectionAdapter $adapter = null) {
        $this->entityClass = $entity;
        $this->alias = $alias;
        $this->entityResolver = Ulmus::resolveEntity($entity);
        $this->adapter = $adapter ?? $this->entityResolver->databaseAdapter();

        $queryBuilder = $this->adapter->adapter()->queryBuilderClass();
        $this->queryBuilder = new $queryBuilder();
    }

    public function __clone()
    {
        #$this->queryBuilder = clone $this->queryBuilder;
    }

    public function loadOne() : ? object
    {
        return $this->limit(1)->selectSqlQuery()->collectionFromQuery()[0] ?? null;
    }

    public function loadOneFromField($field, $value) : ? object
    {
        return $this->where($field, $value)->loadOne();
    }

    public function loadFromPk($value, null|string|\Stringable $primaryKey = null) : ? object
    {
        return $primaryKey ? $this->loadOneFromField($primaryKey, $value) : $this->wherePrimaryKey($value)->loadOne();
    }

    public function loadAll () : EntityCollection
    {
        return $this->selectSqlQuery()->collectionFromQuery();
    }

    public function loadAllFromField($field, $value, $operator= Query\Where::OPERATOR_EQUAL) : EntityCollection
    {
        return $this->loadFromField($field, $value, $operator);
    }

    public function loadFromField($field, $value, $operator= Query\Where::OPERATOR_EQUAL) : EntityCollection
    {
        return $this->selectSqlQuery()->where($field, $value, $operator)->collectionFromQuery();
    }

    public function count() : int
    {
        $this->removeQueryFragment([ Query\Select::class, Query\OrderBy::class,  ]);

        if ( $this->queryBuilder->getFragment(Query\GroupBy::class) ) {
            $this->select( "DISTINCT COUNT(*) OVER ()" );
        }
        else {
            $this->select(Common\Sql::function("COUNT", '*'));
        }

        $this->selectSqlQuery();

        $this->finalizeQuery();

        return Ulmus::runSelectQuery($this->queryBuilder, $this->adapter)->fetchColumn(0);
    }

    public function deleteOne()
    {
        return $this->limit(1)->deleteSqlQuery()->runDeleteQuery();
    }

    public function deleteAll()
    {
        return $this->deleteSqlQuery()->runDeleteQuery();
    }

    public function deleteFromPk($value) : bool
    {
        if ( $value !== 0 && empty($value) ) {
            throw new Exception\EntityPrimaryKeyUnknown("A primary key value has to be defined to delete an item.");
        }

        return (bool) $this->wherePrimaryKey($value, null)->deleteOne()->rowCount;
    }

    public function destroy(object $entity) : bool
    {
        if ( ! $this->matchEntity($entity) ) {
            throw new \Exception("Your entity class `" . get_class($entity) . "` cannot match entity type of repository `{$this->entityClass}`");
        }

        $primaryKeyDefinition = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();

        if ( $primaryKeyDefinition === null ) {
            throw new \Exception(sprintf("No primary key found for entity %s", $this->entityClass));
        }
        else {
            $pkField = key($primaryKeyDefinition);

            return $this->deleteFromPk($entity->$pkField);
        }

        return false;
    }

    public function destroyAll(EntityCollection $collection) : void
    {
        foreach($collection as $entity) {
            $this->destroy($entity);
        }
    }

    public function clone(object|array $entity) : object|false
    {
        $entity = is_object($entity) ? clone $entity : $entity;

        foreach(Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField() as $key => $field) {
            unset($entity->$key);
        }

        return $this->save($entity) ? $entity : false;
    }
    
    public function save(object|array $entity, ? array $fieldsAndValue = null, bool $replace = false) : bool
    {
        if ( is_array($entity) ) {
            $entity = ( new $this->entityClass() )->fromArray($entity);
        }

        if ( ! $this->matchEntity($entity) ) {
            throw new \Exception("Your entity class `" . get_class($entity) . "` cannot match entity type of repository `{$this->entityClass}`");
        }

        $dataset = $entity->toArray();

        $primaryKeyDefinition = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();

        if ( $replace || ! $entity->isLoaded() ) {
            # $dataset = array_filter($dataset, fn($item, $field) => ! ($this->entityResolver->searchFieldAnnotation($field, new Field, false)->readonly ?? false), \ARRAY_FILTER_USE_BOTH);

            $pdoObject = $this->insertSqlQuery($fieldsAndValue ?? $dataset, $replace)->runInsertQuery();

            if ( null !== $primaryKeyDefinition ) {
                $pkField = key($primaryKeyDefinition);

                if ($pdoObject->lastInsertId ) {
                    $dataset[$pkField] = $pdoObject->lastInsertId;
                }
                elseif ($replace) {
                    $pkValue = $dataset[$pkField];
                }
            }

            $entity->entityFillFromDataset($dataset, true);

            return (bool) ( $pkValue ?? $pdoObject->lastInsertId );
        }
        else {
            if ( $primaryKeyDefinition === null ) {
                throw new \Exception(sprintf("No primary key found for entity %s", $this->entityClass));
            }

            $diff = $fieldsAndValue ?? $this->generateWritableDataset($entity);

            if ( [] !== $diff ) {
                $pkField = key($primaryKeyDefinition);
                $pkFieldName = $primaryKeyDefinition[$pkField]->name ?? $pkField;
                $this->where($pkFieldName, $dataset[$pkFieldName]);

                $update = $this->updateSqlQuery($diff)->runUpdateQuery();

                $entity->entityFillFromDataset($dataset, true);

                return $update ? (bool) $update->rowCount : false;
            }
        }

        return false;
    }

    public function saveAll(EntityCollection|array $collection) : int
    {
        $changed = 0;

        foreach ($collection as $entity) {
            $this->save($entity) && $changed++;
        }

        return $changed;
    }

    public function insertAll(EntityCollection|array $collection, int $size = 1000) : int
    {
        if ( empty($collection) ) {
            return 0;
        }
        elseif ( is_array($collection) ) {
            $collection = $this->entityClass::entityCollection($collection);
        }

        foreach($collection as $entity) {
            if  ( ! $this->matchEntity($entity) ) {
                throw new \Exception("Your entity class `" . get_class($entity) . "` cannot match entity type of repository `{$this->entityClass}`");
            }
        }

        $dataset = $entity->toArray();

        $primaryKeyDefinition = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField();

        if ( ! $entity->isLoaded() ) {
            # $dataset = array_filter($dataset, fn($item, $field) => ! ($this->entityResolver->searchFieldAnnotation($field, new Field, false)->readonly ?? false), \ARRAY_FILTER_USE_BOTH);

            $statement = $this->insertSqlQuery($fieldsAndValue ?? $dataset, $replace)->runInsertQuery();

            if ( ( 0 !== $statement->lastInsertId ) &&
                ( null !== $primaryKeyDefinition )) {

                $pkField = key($primaryKeyDefinition);
                $dataset[$pkField] = $statement->lastInsertId;
            }

            $entity->entityFillFromDataset($dataset, true);

            return (bool) $statement->lastInsertId;
        }
        else {
            if ( $primaryKeyDefinition === null ) {
                throw new \Exception(sprintf("No primary key found for entity %s", $this->entityClass));
            }

            $diff = $fieldsAndValue ?? $this->generateWritableDataset($entity);

            if ( [] !== $diff ) {
                $pkField = key($primaryKeyDefinition);
                $pkFieldName = $primaryKeyDefinition[$pkField]->name ?? $pkField;
                $this->where($pkFieldName, $dataset[$pkFieldName]);

                $update = $this->updateSqlQuery($diff)->runUpdateQuery();

                $entity->entityFillFromDataset($dataset, true);

                return $update ? (bool) $update->rowCount : false;
            }
        }

        return 0;
    }

    public function replace(object|array $entity, ? array $fieldsAndValue = null) : bool
    {
        return $this->save($entity, $fieldsAndValue, true);
    }

    public function replaceAll(EntityCollection|array $collection) : int
    {
        $changed = 0;

        foreach($collection as $entity) {
            $this->replace($entity) && $changed++;
        }

        return $changed;
    }

    public function truncate(? string $table = null, ? string $alias = null, ? string $schema = null) : self
    {
        $schema = $schema ?: $this->entityResolver->schemaName();

        $this->queryBuilder->truncate($this->escapeTable($table ?: $this->entityResolver->tableName()), $this->escapeIdentifier($alias ?: $this->alias), $this->escapedDatabase(), $schema ? $this->escapeSchema($schema) : null);

        $this->finalizeQuery();

        # ??? $result = Ulmus::runSelectQuery($this->queryBuilder, $this->adapter);

        return $this;
    }

    public function createTable()
    {
        return $this->createSqlQuery()->runQuery();
    }

    public function alterTable(array $fields)
    {
        return $this->alterSqlQuery($fields)->runQuery();
    }

    public function listTables(? string $database = null)
    {
        return $this->showTablesSqlQuery($database)->runQuery();
    }

    public function listColumns(? string $table = null)
    {
        $table ??= $this->entityResolver->tableName();

        $this->showColumnsSqlQuery($table);

        return $this->collectionFromQuery(Entity\InformationSchema\Column::class);
    }

    public function generateDatasetDiff(object $entity, bool $oldValues = false) : array
    {
        $array = array_change_key_case($entity->toArray());

        $dataset = array_change_key_case($entity->entityGetDataset(false, true));

        return array_udiff_assoc($oldValues ? $dataset : $array , $oldValues ? $array : $dataset, function($e1, $e2) {
            if ( is_array($e1) ) {
                if (is_array($e2)) {
                    return Ulmus::encodeArray($e1) !== Ulmus::encodeArray($e2);
                }
                else {
                    return false;
                }
            }

            return (string) $e1 !== (string) $e2;
        });

        # return array_diff_assoc($oldValues ? $dataset : $array , $oldValues ? $array : $dataset );
    }


    public function generateWritableDataset(object $entity, bool $oldValues = false) : array
    {
        $intersect = [];

        $dataset = $this->generateDatasetDiff($entity, $oldValues);

        foreach($dataset as $field => $value) {
            if ( false === ( $this->entityResolver->searchFieldAnnotation($field, [ Attribute\Property\Field::class, Field::class ], false)->readonly ?? false ) ) {
                $intersect[$field] = $field;
            }
        }

        return array_intersect_key($dataset, $intersect);
    }

    public function yield() : \Generator
    {
        $this->selectSqlQuery();

        $this->finalizeQuery();

        foreach(Ulmus::iterateQueryBuilder($this->queryBuilder, $this->adapter) as $entityData) {
            yield $this->instanciateEntity()->entityFillFromDataset($entityData);
        }
    }

    public function removeQueryFragment(null|Query\Fragment|string|array $fragment) : self
    {
        foreach((array) $fragment as $item) {
            $this->queryBuilder->removeFragment($item);
        }

        return $this;
    }

    public function selectEntity(string $entity, string $alias, string $prependField = "") : self
    {
        $prependField and ($prependField .= "$");

        foreach ($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) {
            if (null === $entity::resolveEntity()->searchFieldAnnotation($field['name'], [ Attribute\Property\Relation\Ignore::class, RelationIgnore::class ])) {
                $this->select(sprintf("%s.$key as {$prependField}{$field['name']}", $this->escapeIdentifier($alias)));
            }
        }

        return $this;
    }

    public function selectJsonEntity(string $entity, string $alias, bool $skipFrom = false) : self
    {
        $fieldlist = [];

        foreach ($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) {
            if (null === $entity::resolveEntity()->searchFieldAnnotation($field['name'], [ Attribute\Property\Relation\Ignore::class, RelationIgnore::class ])) {
                $fieldlist[] = $key;
                $fieldlist[] = $entity::field($field['name'], $this->escapeIdentifier($alias));
            }
        }

        $this->select(
            Common\Sql::function('JSON_ARRAYAGG', Common\Sql::function('JSON_OBJECT', ... $fieldlist))
        );

        return $skipFrom ? $this : $this->from(
            $entity::resolveEntity()->tableName(), $alias, $entity::resolveEntity()->schemaName()
        );
    }

    public function select(array|string|\Stringable $fields, bool $distinct = false) : self
    {
        $this->queryBuilder->select($fields, $distinct);

        return $this;
    }

    public function distinct(array|string|\Stringable $fields) : self
    {
        $this->queryBuilder->select($fields);
        $this->queryBuilder->getFragment(Query\Select::class)->distinct = true;

        return $this;
    }

    public function insert(array $fieldlist, string $table, string $alias, ? string $schema, bool $replace = false) : self
    {
        $this->queryBuilder->insert($fieldlist, $this->escapeTable($table), $this->escapeIdentifier($alias), $this->escapedDatabase(), $schema, $replace);

        return $this;
    }

    public function values(array $dataset) : self
    {
        $this->queryBuilder->values($dataset);
        return $this;
    }

    public function update(string $table, string $alias, ? string $schema) : self
    {
        $this->queryBuilder->update($this->escapeTable($table), $alias ? $this->escapeIdentifier($alias) : null, $this->escapedDatabase(), $schema);

        return $this;
    }

    public function set(array $dataset) : self
    {
        $keys = array_keys($dataset);
        $escapedFields = array_combine($keys, array_map([ $this, 'escapeField' ], $keys));

        $this->queryBuilder->set($dataset, $escapedFields);

        return $this;
    }

    public function delete(...$args) : self
    {
        $this->queryBuilder->delete();

        return $this;
    }

    public function from(string $table, ? string $alias, ? string $schema) : self
    {
        $this->queryBuilder->from($this->escapeTable($table), $alias ? $this->escapeIdentifier($alias) : null, $this->escapedDatabase(), $schema ? $this->escapeSchema($schema) : null);
        
        return $this;
    }

    public function join(string $type, $table, string|\Stringable $field, mixed $value, ? string $alias = null, ? callable $callback = null) : self
    {
        $join = $this->queryBuilder->withJoin($type, $this->escapeTable($table), $field, $value, false, $alias ? $this->escapeIdentifier($alias) : null);

        if ( $callback ) {
            $callback($join);
        }

        return $this;
    }

    public function outerJoin(string $type, $table, string|\Stringable $field, mixed $value, ? string $alias = null, ? callable $callback = null) : self
    {
        $join = $this->queryBuilder->withJoin($type, $this->escapeTable($table), $field, $value, true, $alias ? $this->escapeIdentifier($alias) : null);

        if ( $callback ) {
            $callback($join);
        }

        return $this;
    }

    public function match() : self
    {

    }

    public function notMatch() : self
    {

    }

    public function between() : self
    {

    }

    public function notBetween() : self
    {

    }

    public function groupBy(string|\Stringable $field) : self
    {
        $this->queryBuilder->groupBy($field);

        return $this;
    }

    public function groups(array $groups) : self
    {
        foreach($groups as $field ) {
            $this->groupBy($field);
        }

        return $this;
    }

    public function orderBy(string|object $field, ? string $direction = null) : self
    {
        $this->queryBuilder->orderBy($field, $direction);

        return $this;
    }

    # @UNTESTED
    public function randomizeOrder() : self
    {
        $this->queryBuilder->orderBy(Common\Sql::function('RAND', Sql::identifier('CURDATE()+0')));

        return $this;
    }

    public function orders(array $orderList) : self
    {
        foreach($orderList as $field => $direction) {
            if (is_numeric($field)) {
                $this->orderBy($direction);
            }
            else {
                # Associative array with direction
                $this->orderBy($field, $direction);
            }
        }

        return $this;
    }

    public function limit(int $value) : self
    {
        $this->queryBuilder->limit($value);

        return $this;
    }

    public function offset(int $value) : self
    {
        $this->queryBuilder->offset($value);

        return $this;
    }

    /* @TODO */
    public function commit() : self
    {
        return $this;
    }

    /* @TODO */
    public function rollback() : self
    {
        return $this;
    }

    public function wherePrimaryKey(mixed $value, null|string|bool $alias = self::DEFAULT_ALIAS) : self
    {
        if ( null === $primaryKeyField = Ulmus::resolveEntity($this->entityClass)->getPrimaryKeyField() ) {
            throw new Exception\EntityPrimaryKeyUnknown("Entity has no field containing attributes 'primary_key'");
        }

        $pkField = key($primaryKeyField);

        return $this->where($this->entityClass::field($primaryKeyField[$pkField]->name ?? $pkField, $alias), $value);
    }

    public function withJoin(string|array $fields, array $options = []) : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Select::class) ) {
            $select = $this->entityResolver->fieldList(EntityResolver::KEY_COLUMN_NAME, true);
            $this->select($this->entityClass::fields(array_map(fn($f) => $f['object']->name ?? $f['name'], $select)));
        }

        # @TODO Apply FILTER annotation to this too !
        foreach(array_filter((array) $fields) as $item) {
            if ( isset($this->joined[$item]) ) {
                continue;
            }
            else {
                $this->joined[$item] = true;
            }

            $annotation = $this->entityResolver->searchFieldAnnotation($item, [ Attribute\Property\Join::class, Join::class ]) ?:
                $this->entityResolver->searchFieldAnnotation($item, [ Attribute\Property\Relation::class, Relation::class ]);

            $isRelation = ( $annotation instanceof Relation ) || ($annotation instanceof Attribute\Property\Relation);

            if ($isRelation && ( $annotation->isManyToMany() )) {
                throw new Exception("Many-to-many relation can not be preloaded within joins.");
            }

            if ( $annotation ) {
                $alias = $annotation->alias ?? $item;

                $entity = $annotation->entity ?? $this->entityResolver->properties[$item]['type'];

                foreach($entity::resolveEntity()->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) {
                    if ( null === $entity::resolveEntity()->searchFieldAnnotation($field['name'], [ Attribute\Property\Relation\Ignore::class, RelationIgnore::class ]) ) {
                        $escAlias = $this->escapeIdentifier($alias);
                        $fieldName = $this->escapeIdentifier($key);

                        $name = $entity::resolveEntity()->searchFieldAnnotation($field['name'], [ Attribute\Property\Field::class, Field::class ])->name ?? $field['name'];


                        $this->select("$escAlias.$fieldName as $alias\${$name}");
                    }
                }

                $this->open();

                if ( ! in_array(WithOptionEnum::SkipWhere, $options)) {
                foreach($this->entityResolver->searchFieldAnnotationList($item, [ Attribute\Property\Where::class, Where::class ] ) as $condition) {
                    if ( is_object($condition->field) && ( $condition->field->entityClass !== $entity ) ) {
                        $this->where(is_object($condition->field) ? $condition->field : $entity::field($condition->field),  $condition->getValue(), $condition->operator);
                    }
                }
                }

                if ( ! in_array(WithOptionEnum::SkipHaving, $options)) {
                    foreach ($this->entityResolver->searchFieldAnnotationList($item, [Attribute\Property\Having::class, Having::class]) as $condition) {
                        $this->having(is_object($condition->field) ? $condition->field : $entity::field($condition->field), $condition->getValue(), $condition->operator);
                    }
                }

                if ( ! in_array(WithOptionEnum::SkipFilter, $options)) {
                    foreach ($this->entityResolver->searchFieldAnnotationList($item, [Attribute\Property\Filter::class, Filter::class]) as $filter) {
                        call_user_func_array([$this->entityClass, $filter->method], [$this, $item, true]);
                    }
                }

                $this->close();

                $key = is_string($annotation->key) ? $this->entityClass::field($annotation->key) : $annotation->key;

                $foreignKey = is_string($annotation->foreignKey) ? $entity::field($annotation->foreignKey, $alias) : $annotation->foreignKey;

                $this->join("LEFT", $entity::resolveEntity()->tableName(), $key, $foreignKey, $alias, function($join) use ($item, $entity, $alias, $options) {
                    if (  !  in_array(WithOptionEnum::SkipJoinWhere, $options)) {
                    foreach($this->entityResolver->searchFieldAnnotationList($item, [ Attribute\Property\Where::class, Where::class ]) as $condition) {
                        if ( ! is_object($condition->field) ) {
                            $field = $this->entityClass::field($condition->field);
                        }
                        else {
                            $field = clone $condition->field;
                        }

                        # Adding directly
                        if ( $field->entityClass === $entity ) {
                            $field->alias = $alias;

                            $join->where(is_object($field) ? $field : $entity::field($field, $alias), $condition->getValue(), $condition->operator);
                        }
                    }
                    }

                    if ( ! in_array(WithOptionEnum::SkipJoinFilter, $options) ) {
                         foreach ($this->entityResolver->searchFieldAnnotationList($item, [Attribute\Property\FilterJoin::class, FilterJoin::class]) as $filter) {
                            call_user_func_array([$this->entityClass, $filter->method], [$join, $item, true]);
                        }
                    }
                });
            }
            else {
                throw new \Exception("Referenced field `$item` which do not exist or do not contain a valid @Join or @Relation annotation.");
            }
        }

        return $this;
    }

    public function withSubquery(string|array $fields, array $options = []) : self
    {
        # We skip subqueries when counting results since it should not affect the row count.
        if ( $this instanceof Repository\ServerRequestCountRepository ) {
            return $this;
        }

        if ( null === $this->queryBuilder->getFragment(Query\Select::class) ) {
            $this->select($this->escapeIdentifier($this->alias) . ".*");
        }

        # Apply FILTER annotation to this too !
        foreach(array_filter((array) $fields) as $item) {
            if ( $relation = $this->entityResolver->searchFieldAnnotation($item, [ Attribute\Property\Relation::class, Relation::class ]) ) {
                $alias = $relation->alias ?? $item;

                if ( $relation->isManyToMany() ) {
                    $entity = $relation->bridge;
                    $repository = $relation->bridge::repository();
                    $repository->queryBuilder->parent = $this->queryBuilder;

                    extract(Repository\RelationBuilder::relationAnnotations($item, $relation));

                    $repository->join(Query\Join::TYPE_INNER, $bridgeEntity->tableName(), $relation->bridge::field($relationRelation->key, $relation->bridgeField), $relationRelation->entity::field($relationRelation->foreignKey, $alias), $relation->bridgeField)
                        ->where( $entity::field($bridgeRelation->key, $relation->bridgeField), $entity::field($bridgeRelation->foreignKey, $this->alias))
                        ->selectJsonEntity($relationRelation->entity, $alias)->open();
                }
                else {
                    $entity = $relation->entity ?? $this->entityResolver->properties[$item]['type'];
                    $repository = $entity::repository()->selectJsonEntity($entity, $alias)->open();
                }

                #  $relation->isManyToMany() and $repository->selectJsonEntity($relation->bridge, $relation->bridgeField, true);

                foreach($this->entityResolver->searchFieldAnnotationList($item, [ Attribute\Property\Where::class, Where::class ]) as $condition) {
                    $repository->where(is_object($condition->field) ? $condition->field : $entity::field($condition->field), $condition->getValue(), $condition->operator);
                }

                foreach($this->entityResolver->searchFieldAnnotationList($item, [ Attribute\Property\Having::class, Having::class ] ) as $condition) {
                    $repository->having(is_object($condition->field) ? $condition->field : $entity::field($condition->field), $condition->getValue(), $condition->operator);
                }

                $repository->close();

                $key = is_string($relation->key) ? $this->entityClass::field($relation->key) : $relation->key;

                if (! $relation->isManyToMany() ) {
                    $foreignKey = is_string($relation->foreignKey) ? $entity::field($relation->foreignKey, $alias) : $relation->foreignKey;

                    $repository->where( $foreignKey, $key);
                }

                $this->select("(" . $r = Common\Sql::raw($repository->queryBuilder->render() . ") as $item\$collection"));
            }
            else {
                throw new \Exception("You referenced field `$item` which do not exist or do not contain a valid @Join annotation.");
            }
        }

        return $this;
    }

    public function loadCollectionRelation(EntityCollection $collection, array|string $fields) : void
    {
        foreach ((array)$fields as $name) {
            if (null !== ($relation = $this->entityResolver->searchFieldAnnotation($name, [ Attribute\Property\Relation::class, Relation::class ] ))) {
                $order = $this->entityResolver->searchFieldAnnotationList($name, [ Attribute\Property\OrderBy::class, OrderBy::class ]);
                $where = $this->entityResolver->searchFieldAnnotationList($name, [ Attribute\Property\Where::class, Where::class ]);

                $baseEntity = $relation->entity ?? $relation->bridge ?? $this->entityResolver->properties[$name]['type'];
                $baseEntityResolver = $baseEntity::resolveEntity();

                $property = ($baseEntityResolver->field($relation->foreignKey, 01, false) ?: $baseEntityResolver->field($relation->foreignKey, 02))['name'];
                $entityProperty = ($this->entityResolver->field($relation->key, 01, false) ?: $this->entityResolver->field($relation->key, 02))['name'];

                $repository = $baseEntity::repository();

                foreach ($baseEntityResolver->fieldList(Common\EntityResolver::KEY_COLUMN_NAME, true) as $key => $field) {
                    if (null === $baseEntityResolver->searchFieldAnnotation($field['name'], [ Attribute\Property\Relation\Ignore::class, RelationIgnore::class ])) {
                        $repository->select($baseEntityResolver->entityClass::field($key));
                    }
                }

                foreach ($where as $condition) {
                    # $repository->where($condition->field, is_callable($condition->value) ? call_user_func_array($condition->value, [$this]) : $condition->getValue(), $condition->operator, $condition->condition);
                    $repository->where($condition->field, $condition->getValue($this), $condition->operator, $condition->condition);
                }

                foreach ($order as $item) {
                    $repository->orderBy($item->field, $item->order);
                }

                $field = $relation->key;

                $values = [];

                $key = is_object($relation->foreignKey) ? $relation->foreignKey : $baseEntity::field($relation->foreignKey);

                foreach ($collection as $item) {
                    $values[] = is_callable($field) ? $field($item) : $item->$entityProperty;
                }

                $values = array_unique($values);

                $repository->where($key, $values);

                $results = $repository->loadAll();

                if ($relation->isOneToOne()) {
                    foreach ($collection as $item) {
                        $item->$name = $results->searchOne($item->$entityProperty, $property) ?: new $baseEntity();
                    }
                }
                elseif ($relation->isOneToMany()) {
                    foreach ($collection as $item) {
                        $item->$name = $baseEntity::entityCollection();
                        $item->$name->mergeWith($results->searchAll($item->$entityProperty, $property));
                    }
                }
            }
        }
    }

    public function filterServerRequest(SearchRequest\SearchRequestInterface $searchRequest, bool $count = true) : self
    {
        if ($count) {
            $searchRequest->count = $searchRequest->filter($this->serverRequestCountRepository())
                ->wheres($searchRequest->wheres(), Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
                ->likes($searchRequest->likes(), Query\Where::CONDITION_OR)
                ->groups($searchRequest->groups())
                ->count();
        }

        return $searchRequest->filter($this)
            ->wheres($searchRequest->wheres(), Query\Where::OPERATOR_EQUAL, Query\Where::CONDITION_AND)
            ->likes($searchRequest->likes(), Query\Where::CONDITION_OR)
            ->orders($searchRequest->orders())
            ->groups($searchRequest->groups())
            ->offset($searchRequest->offset())
            ->limit($searchRequest->limit());
    }

    protected function serverRequestCountRepository() : Repository
    {
        return new Repository\ServerRequestCountRepository($this->entityClass, $this->alias, $this->adapter);
    }

    public function collectionFromQuery(? string $entityClass = null) : EntityCollection
    {
        $entityClass ??= $this->entityClass;

        $entityCollection = $entityClass::entityCollection();

        $this->finalizeQuery();
        
        foreach(Ulmus::iterateQueryBuilder($this->queryBuilder, $this->adapter) as $entityData) {
            $entity = $this->instanciateEntity($entityClass);
            $entity->loadedFromAdapter = $this->adapter->name;

            $entityCollection->append( $entity->resetVirtualProperties()->entityFillFromDataset($entityData) );
        }

        $this->eventExecute(Event\Repository\CollectionFromQueryInterface::class, $entityCollection);

        return $entityCollection;
    }

    public function arrayFromQuery() : array
    {
        $this->selectSqlQuery();

        $this->finalizeQuery();

        return Ulmus::datasetQueryBuilder($this->queryBuilder, $this->adapter);
    }

    public function runQuery() : mixed
    {
        $this->finalizeQuery();

        return Ulmus::runQuery($this->queryBuilder, $this->adapter);
    }

    public function runInsertQuery() : mixed
    {
        $this->finalizeQuery();

        return Ulmus::runInsertQuery($this->queryBuilder, $this->adapter);
    }

    public function runUpdateQuery() : mixed
    {
        $this->finalizeQuery();

        return Ulmus::runUpdateQuery($this->queryBuilder, $this->adapter);
    }

    public function runDeleteQuery() : mixed
    {
        $this->finalizeQuery();

        return Ulmus::runDeleteQuery($this->queryBuilder, $this->adapter);
    }

    public function resetQuery() : self
    {
        $this->queryBuilder->reset();

        return $this;
    }

    protected function insertSqlQuery(array $dataset, bool $replace = false) : self
    {
        if ( null === $insert = $this->queryBuilder->getFragment(Query\Insert::class) ) {
            $this->insert(array_map([ $this, 'escapeField' ] , array_keys($dataset)), $this->entityResolver->tableName(), $this->alias, $this->entityResolver->schemaName(), $replace);
        }
        else {
            $insert->replace = $replace;
        }

        $this->values($dataset);

        return $this;
    }

    protected function updateSqlQuery(array $dataset) : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Update::class) ) {
            $this->update($this->entityResolver->tableName(), $this->alias, $this->entityResolver->schemaName());
        }

        $this->set($dataset);

        return $this;
    }

    protected function selectSqlQuery() : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Select::class) ) {
            $fields = $this->entityResolver->fieldList(EntityResolver::KEY_COLUMN_NAME, true);
            $this->select($this->entityClass::fields(array_map(fn($f) => $f['object']->name ?? $f['name'], $fields)));
        }

        if ( null === $this->queryBuilder->getFragment(Query\From::class) ) {
            $this->from($this->entityResolver->tableName(), $this->alias, $this->entityResolver->schemaName());
        }

        return $this;
    }

    protected function deleteSqlQuery() : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Delete::class) ) {
            $this->delete();
        }

        if ( null === $this->queryBuilder->getFragment(Query\From::class) ) {
            $this->from($this->entityResolver->tableName(), null, $this->entityResolver->schemaName());
        }

        return $this;
    }

    public function createSqlQuery() : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Create::class) ) {
            $this->queryBuilder->create($this->adapter->adapter(), $this->escapeFieldList($this->entityResolver->fieldList(EntityResolver::KEY_ENTITY_NAME, true)), $this->escapeTable($this->entityResolver->tableName()), $this->entityResolver->schemaName());
        }

        return $this;
    }

    public function alterSqlQuery(array $fields) : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Alter::class) ) {
            $this->queryBuilder->alter($this->adapter->adapter(), $fields, $this->escapeTable($this->entityResolver->tableName()), $this->entityResolver->schemaName());
        }

        return $this;
    }

    public function showDatabasesSqlQuery() : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Show::class) ) {
            $this->queryBuilder->showDatabases();
        }

        return $this;
    }

    public function showTablesSqlQuery() : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Show::class) ) {
            $this->queryBuilder->showTables();
        }

        return $this;
    }

    public function showColumnsSqlQuery(string $table) : self
    {
        if ( null === $this->queryBuilder->getFragment(Query\Show::class) ) {
            $this->queryBuilder->showColumns($table);
        }

        return $this;
    }

    protected function fromRow($row) : self
    {

    }

    protected function fromCollection($rows) : self
    {

    }

    public function getSqlQuery(bool $flush = true) : string
    {
        $result = $this->queryBuilder->render();

        $flush and $this->queryBuilder->reset();

        return $result;
    }

    public function instanciateEntityCollection(...$arguments) : EntityCollection
    {
        return $this->entityClass::entityCollection(...$arguments);
    }

    public function instanciateEntity(? string $entityClass = null) : object
    {
        $entityClass ??= $this->entityClass;

        return new $entityClass;
    }

    public function hasFilters() : bool
    {
        return isset($this->queryBuilder->where);
    }

    protected function matchEntity(object $entity) {
        return $entity::class === $this->entityClass;
    }

    protected function finalizeQuery() : void {}
}