<?php
/**
 * @author Daniel J. Summers <daniel@bitbadger.solutions>
 * @license MIT
 * @see https://github.com/Zaid-Ajaj/ThrowawayDb The origin concept
 */

declare(strict_types=1);

namespace Test\Integration;

use BitBadger\PDODocument\{Configuration, Custom, Delete, DocumentException, Field};
use BitBadger\PDODocument\Mapper\ExistsMapper;
use PHPUnit\Framework\TestCase;
use Test\Integration\PostgreSQL\ThrowawayDb;

/**
 * Integration Test Class wrapper for PostgreSQL integration tests
 */
class PgIntegrationTest extends TestCase
{
    /** @var string Database name for throwaway database */
    static private string $dbName = '';

    public static function setUpBeforeClass(): void
    {
        self::$dbName = ThrowawayDb::create(false);
    }

    protected function setUp(): void
    {
        parent::setUp();
        ThrowawayDb::loadData();
    }

    protected function tearDown(): void
    {
        Delete::byFields(ThrowawayDb::TABLE, [ Field::exists(Configuration::$idField)]);
        parent::tearDown();
    }

    public static function tearDownAfterClass(): void
    {
        ThrowawayDb::destroy(self::$dbName);
        self::$dbName = '';
    }

    /**
     * Does the given named object exist in the database?
     *
     * @param string $name The name of the object whose existence should be verified
     * @return bool True if the object exists, false if not
     * @throws DocumentException If any is encountered
     */
    protected function dbObjectExists(string $name): bool
    {
        return Custom::scalar('SELECT EXISTS (SELECT 1 FROM pg_class WHERE relname = :name)',
            [':name' => $name], new ExistsMapper());
    }
}