<?php

namespace Tests\Unit\Framework;

use InvalidArgumentException;
use Openguru\OpenCartFramework\QueryBuilder\Builder;
use Openguru\OpenCartFramework\QueryBuilder\Connections\MySqlConnection;
use Openguru\OpenCartFramework\QueryBuilder\Grammars\MySqlGrammar;
use Openguru\OpenCartFramework\QueryBuilder\Table;
use Tests\TestCase;

class TableTest extends TestCase
{
    public function testGetTableString(): void
    {
        $table = new Table('table1');

        $this->assertEquals('table1', $table->getTable());
    }

    public function testToStringSub(): void
    {
        $connection = new MySqlConnection($this->getPdoMock());
        $builder = new Builder($connection, new MySqlGrammar());

        $subQuery = $builder->newQuery()
            ->select(['id'])
            ->from('table1');

        $table = new Table($subQuery, 'tbl_alias');

        $this->assertEquals('(SELECT id FROM table1) AS tbl_alias', (string) $table);
    }

    public function testThrowsExceptionForSubWithoutAlias(): void
    {
        $this->expectException(InvalidArgumentException::class);

        $connection = new MySqlConnection($this->getPdoMock());
        $builder = new Builder($connection, new MySqlGrammar());

        $subQuery = $builder->newQuery()
            ->select(['id'])
            ->from('table1');

        new Table($subQuery);
    }

    public function testGetAlias(): void
    {
        $table = new Table('table1', 'alias');

        $this->assertEquals('alias', $table->getAlias());
    }
}
