<?php

namespace Sibs\DB;

use Configuration;
use Exception;
use Sibs\Models\SibsCardTokens;
use Sibs\Models\SibsOrderRef;
use Sibs\Models\SibsOrderRefLog;
use Sibs\Models\SibsTerminal;
use Sibs\Models\SibsTransaction;
use Sibs\Models\SibsWebhookCalls;
use Sibs\SibsLogger;

class SibsMigration
{
    private const TABLE_METHOD  = 'getStaticTableName';
    private const CONFIG_METHOD = 'getStaticConfigName';
    private const CREATE_METHOD = 'create';

    /**
     * Execute Migration.
     *
     * @return bool
     */
    public static function execute(): bool
    {
        return
            self::migrateClass(SibsOrderRef::class) &&
            self::migrateClass(SibsOrderRefLog::class) &&
            self::migrateClass(SibsCardTokens::class) &&
            self::migrateClass(SibsTerminal::class) &&
            self::migrateClass(SibsWebhookCalls::class) &&
            self::migrateClass(SibsTransaction::class);
    }

    /**
     * Migrate Class.
     *
     * @param string $tableClass
     * @return bool
     */
    private static function migrateClass($tableClass): bool
    {
        $tableName  = call_user_func_array([$tableClass, self::TABLE_METHOD], []);
        $configName = call_user_func_array([$tableClass, self::CONFIG_METHOD], []);

        if (Configuration::get($configName) == '1') {
            return true;
        }

        try {
            SibsLogger::info('Creating ' . $tableName . ' table');

            $response = call_user_func_array([$tableClass, self::CREATE_METHOD], []);

            if ($response == false) {
                throw new Exception('General Error');
            }

            SibsLogger::info('Created ' . $tableName . ' table');

            Configuration::updateValue($configName, '1');

            return true;
        } catch (Exception $e) {
            SibsLogger::error('Error on Creating ' . $tableName . ' table: ' . $e->getMessage());

            Configuration::updateValue($configName, '0');

            return false;
        }
    }
}
