<?php

namespace Tests\Helpers;

use Doctrine\SqlFormatter\NullHighlighter;
use Doctrine\SqlFormatter\SqlFormatter;
use Mockery;
use Openguru\OpenCartFramework\QueryBuilder\Connections\ConnectionInterface;
use PDO;

trait DatabaseHelpers
{
    public function dropAllTables(): void
    {
        /** @var ConnectionInterface $database */
        $database = $this->app->get(ConnectionInterface::class);
        $databaseName = getenv('DB_DATABASE');

        $sql = <<<SQL
            SELECT TABLE_NAME
            FROM information_schema.tables
            WHERE table_schema = ?
        SQL;

        $tables = $database->select($sql, [$databaseName]);
        $tables = array_column($tables, 'TABLE_NAME');

        foreach ($tables as $table) {
            $database->dropTable($table);
        }
    }

    public function getPdoMock()
    {
        $pdoMock = Mockery::spy(PDO::class);
        $pdoMock->shouldReceive('quote')
            ->andReturnUsing(function ($value) {
                return "'$value'";
            });

        return $pdoMock;
    }

    public function formatSql(string $query): string
    {
        return (new SqlFormatter(new NullHighlighter()))->format($query);
    }

    public function createRandomTable(): string
    {
        $randomTableName = 'tbl_random_' . uniqid('', true);
        $randomTableName = str_replace('.', '_', $randomTableName);

        /** @var ConnectionInterface $database */
        $database = $this->app->get(ConnectionInterface::class);
        $database->statement("CREATE TABLE $randomTableName (id INT AUTO_INCREMENT PRIMARY KEY)");

        return $randomTableName;
    }
}