<?php

namespace App\Modules\Shared\Domain\QueryBuilder;

use App\Modules\Shared\Domain\Aggregate\AggregateAttribute;

class QueryTable
{

    /** @return AggregateAttribute[] */
    private array $attributes;

    public function __construct(
        public $table,
        public $modelClass,
        public $alias,
    ) {
        $this->attributes = $modelClass::attributes();
    }

    public function column($column)
    {
        return "`{$this->alias}`.`{$column->column()}`";
    }

    public function exists($dto): bool
    {
        if ($dto === null) {
            return false;
        }

        $data = array_values(array_filter(array_map(function (AggregateAttribute $attr) use ($dto) {
            if ($dto->{$attr->uniqueId()} === null) {
                return null;
            }
            return $dto->{$attr->uniqueId()};
        }, $this->attributes), fn($value) => $value !== null));
        return count($data) > 0;
    }

    public function createFromDTO($dto)
    {
        return $this->modelClass::fromDTOUnique($dto, $this->attributes);
    }

    public function getSelectedFields()
    {
        return $this->modelClass::selectUnique('`' . $this->alias . '`', $this->attributes);
    }
}
