<?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\PostgreSQL;

use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, DocumentException};
use Random\RandomException;
use Test\Integration\{SubDocument, TestDocument};

/**
 * Utilities to create and destroy a throwaway PostgreSQL database to use for testing
 */
class ThrowawayDb
{
    /** @var string The table used for document manipulation */
    public const TABLE = 'test_table';

    /**
     * Configure the document library for the given database (or the main PostgreSQL connection, if the database name
     * is not provided; this is used for creating and dropping databases)
     *
     * @param string|null $dbName The name of the database to configure (optional, defaults to env or "postgres")
     * @throws DocumentException If any is encountered
     */
    private static function configure(?string $dbName = null): void
    {
        Configuration::useDSN(sprintf("pgsql:host=%s;dbname=%s", $_ENV['PDO_DOC_PGSQL_HOST'] ?? 'localhost',
            $dbName ?? $_ENV['PDO_DOC_PGSQL_DB'] ?? 'postgres'));
        Configuration::$username = $_ENV['PDO_DOC_PGSQL_USER'] ?? 'postgres';
        Configuration::$password = $_ENV['PDO_DOC_PGSQL_PASS'] ?? 'postgres';
        Configuration::resetPDO();
    }

    /**
     * Create a throwaway PostgreSQL database
     *
     * @param bool $withData Whether to initialize this database with data (optional; defaults to `true`)
     * @return string The name of the database (use to pass to `destroy` function at end of test)
     * @throws DocumentException|RandomException If any is encountered
     */
    public static function create(bool $withData = true): string
    {
        $dbName = 'throwaway_' . AutoId::generateRandom(10);
        self::configure();
        Custom::nonQuery("CREATE DATABASE $dbName WITH OWNER " . Configuration::$username, []);
        self::configure($dbName);

        if ($withData) {
            Definition::ensureTable(self::TABLE);
            Document::insert(self::TABLE, new TestDocument('one', 'FIRST!', 0));
            Document::insert(self::TABLE, new TestDocument('two', 'another', 10, new SubDocument('green', 'blue')));
            Document::insert(self::TABLE, new TestDocument('three', '', 4));
            Document::insert(self::TABLE, new TestDocument('four', 'purple', 17, new SubDocument('green', 'red')));
            Document::insert(self::TABLE, new TestDocument('five', 'purple', 18));
        }

        return $dbName;
    }

    /**
     * Destroy a throwaway PostgreSQL database
     *
     * @param string $dbName The name of the PostgreSQL database to be dropped
     * @throws DocumentException If any is encountered
     */
    public static function destroy(string $dbName): void
    {
        self::configure();
        Custom::nonQuery("DROP DATABASE IF EXISTS $dbName WITH (FORCE)", []);
        Configuration::useDSN('');
        Configuration::$username = null;
        Configuration::$password = null;
        Configuration::resetPDO();
    }
}