from rhodecode.lib.dbmigrate.versions import _reset_base
from rhodecode.model import meta, init_model_encryption


def upgrade(migrate_engine):
    """
    Add Git default branch configuration
    """
    _reset_base(migrate_engine)

    from rhodecode.lib.dbmigrate.schema import db_4_20_0_1 as db

    init_model_encryption(db)

    from rhodecode.model.db import RhodeCodeUi

    session = meta.Session()

    # Check if setting already exists
    existing = (
        session.query(RhodeCodeUi)
        .filter(RhodeCodeUi.ui_section == "vcs_git", RhodeCodeUi.ui_key == "default_branch")
        .first()
    )

    if not existing:
        # Add default branch setting with 'master' as default
        setting = RhodeCodeUi()
        setting.ui_section = "vcs_git"
        setting.ui_key = "default_branch"
        setting.ui_value = "master"
        setting.ui_active = True
        session.add(setting)
        session.commit()


def downgrade(migrate_engine):
    """
    Remove Git default branch configuration
    """
    _reset_base(migrate_engine)

    from rhodecode.lib.dbmigrate.schema import db_4_20_0_1 as db

    init_model_encryption(db)

    from rhodecode.model.db import RhodeCodeUi

    session = meta.Session()
    session.query(RhodeCodeUi).filter(
        RhodeCodeUi.ui_section == "vcs_git", RhodeCodeUi.ui_key == "default_branch"
    ).delete()
    session.commit()
