<?php

namespace Sibs\DB\Seeds;

use Configuration;
use Exception;
use Sibs\Models\SibsModels;
use Sibs\SibsLogger;

abstract class AbstractSeed
{
    private const SEED_NAME_METHOD = 'getStaticSeedName';
    private const SEED_METHOD      = 'seed';

    /**
     * Get Static Seed Name.
     *
     * @return bool
     */
    abstract public static function getStaticSeedName(): string;

    /**
     * Get Static Config Name.
     *
     * @return bool
     */
    abstract public static function getStaticConfigName(): string;

    /**
     * Seed.
     *
     * @param SibsModels $model
     * @return bool
     */
    abstract public static function seed(SibsModels $model): bool;

    /**
     * Seed Function.
     *
     * @param SibsModels $tableClass
     * @param string $seedClass
     * @param string $configName
     * @return bool
     */
    protected static function seedFunction(SibsModels $tableClass, $seedClass, $configName): bool
    {
        $seedName = call_user_func_array([$seedClass, self::SEED_NAME_METHOD], []);

        if (Configuration::get($configName) != '1') {
            try {
                SibsLogger::info('Seeding ' . $seedName . ' table');

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

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

                SibsLogger::info('Seeded ' . $seedName . ' table');

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

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

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

                return false;
            }
        }

        return true;
    }
}
