from core.database.database_settings import DatabaseSettings
from core.database.db_context import DBContext
from core.environment import Environment
from core.logger import DBLogger

logger = DBLogger(__name__)


class Database:
    _db = None

    @classmethod
    def init(
        cls,
        db: DBContext,
    ):
        cls._db: DBContext = db

    @classmethod
    def connect(cls):
        cls._db.connect()

    @classmethod
    async def startup_db(cls):
        from data.service.migration_service import MigrationService

        logger.info("Init DB")
        db = DBContext()
        host = Environment.get("DB_HOST", str)
        port = Environment.get("DB_PORT", int)
        user = Environment.get("DB_USER", str)
        password = Environment.get("DB_PASSWORD", str)
        database = Environment.get("DB_DATABASE", str)

        if None in [host, port, user, password, database]:
            logger.fatal(
                "DB settings are not set correctly",
                EnvironmentError("DB settings are not set correctly"),
            )

        await db.connect(
            DatabaseSettings(
                host=host, port=port, user=user, password=password, database=database
            )
        )
        Database.init(db)
        migrations = MigrationService(db)
        await migrations.migrate()
