"""Allow `log` as a proactive feature-management permission value.

Relaxes the CHECK constraint on
``feature_management_permissions.proactive`` from
``(NA, FULL)`` to ``(NA, LOG, FULL)``. SQLite cannot alter CHECK
constraints in place, so the table is recreated.

DEF-42523.
"""
from peewee import CharField, Check, Model, TextField

from defence360agent.feature_management.constants import (
    AV_REPORT,
    FULL,
    LOG,
    NA,
)


class FeatureManagementPerms(Model):
    class Meta:
        db_table = "feature_management_permissions"

    user = CharField(unique=True)
    proactive = TextField(
        null=False,
        constraints=[
            Check("proactive in ('{}','{}','{}')".format(NA, LOG, FULL))
        ],
        default=FULL,
    )
    av = TextField(
        null=False,
        constraints=[
            Check("av in ('{}','{}','{}')".format(NA, AV_REPORT, FULL))
        ],
        default=AV_REPORT,
    )


def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return
    migrator.sql(
        "ALTER TABLE feature_management_permissions "
        "RENAME TO feature_management_permissions_old"
    )
    migrator.create_model(FeatureManagementPerms)
    migrator.sql(
        "INSERT INTO feature_management_permissions(user, proactive, av) "
        "SELECT user, proactive, av FROM feature_management_permissions_old"
    )
    migrator.sql("DROP TABLE feature_management_permissions_old")


def rollback(migrator, database, fake=False, **kwargs):
    pass
