<?php

namespace Openguru\OpenCartFramework\QueryBuilder;

use InvalidArgumentException;
use Stringable;

class Table implements Stringable
{
    private $table;
    private ?string $alias;

    /**
     * @param string|Builder $table
     * @param string|null $alias
     */
    public function __construct($table, ?string $alias = null)
    {
        $this->table = $table;
        $this->alias = $alias;

        if ($this->table instanceof Builder && ! $this->getAlias()) {
            throw new InvalidArgumentException('Alias required for Sub Queries');
        }
    }

    /**
     * @return Builder|string
     */
    public function getTable()
    {
        return $this->table;
    }

    public function getAlias(): ?string
    {
        return $this->alias;
    }

    public function __toString(): string
    {
        $table = $this->getTable();
        $alias = $this->getAlias();

        if ($table instanceof Builder) {
            $table = '(' . $table->toRawSql() . ')';
        }

        return $table . ($alias ? ' AS ' . $alias : '');
    }
}
