<?php

namespace ipl\Orm;

use ipl\Sql\Select;

class UnionQuery extends Query
{
    /** @var ?Query[] Underlying queries */
    private ?array $unions = null;

    /**
     * Get the underlying queries
     *
     * @return Query[]
     */
    public function getUnions(): array
    {
        if ($this->unions === null) {
            $this->unions = [];

            /** @var UnionModel $model */
            $model = $this->getModel();
            foreach ($model->getUnions() as [$target, $relations, $columns]) {
                /** @var class-string<Model> $target */
                $query = $target::on($this->getDb())
                    ->columns($columns)
                    ->disableDefaultSort()
                    ->with($relations);

                $this->unions[] = $query;
            }
        }

        return $this->unions;
    }

    public function getSelectBase(): Select
    {
        if ($this->selectBase === null) {
            $this->selectBase = new Select();
        }

        $union = new Select();

        foreach ($this->getUnions() as $query) {
            $select = $query->assembleSelect();
            $columns = $select->getColumns();
            $select->resetColumns();
            ksort($columns);
            $select->columns($columns);

            $union->unionAll($select);
        }

        $this->selectBase->from([$this->getModel()->getTableName() => $union]);

        return $this->selectBase;
    }
}
