from time import time

import peewee as pw


def migrate(migrator, database, fake=False, **kwargs):
    class ProactiveIgnoredPath(pw.Model):
        """
        Ignore list for proactive defence
        """

        path = pw.TextField(null=False, primary_key=True)
        timestamp = pw.IntegerField(null=False, default=time)

        class Meta:
            db_table = "proactive_ignored_path"

    class ProactiveIgnoredRule(pw.Model):
        """
        Specific rules ignored
        """

        path = pw.ForeignKeyField(
            ProactiveIgnoredPath,
            null=False,
            on_delete="CASCADE",
            related_name="rules",
        )
        rule_id = pw.IntegerField(null=False)
        rule_name = pw.TextField(null=False)

        class Meta:
            db_table = "proactive_ignored_rule"
            indexes = ((("path", "rule_id"), True),)

    migrator.create_model(ProactiveIgnoredPath)
    migrator.create_model(ProactiveIgnoredRule)

    Proactive = migrator.orm["proactive"]
    migrator.add_fields(
        Proactive,
        rule_id=pw.IntegerField(null=True),
    )
    migrator.rename_field(Proactive, "reason", "rule_name")


def rollback(migrator, database, fake=False, **kwargs):
    ProactiveIgnoredPath = migrator.orm["proactive_ignored_path"]
    ProactiveIgnoredRule = migrator.orm["proactive_ignored_rule"]
    migrator.remove_model(ProactiveIgnoredRule)
    migrator.remove_model(ProactiveIgnoredPath)

    Proactive = migrator.orm["proactive"]
    migrator.remove_fields(Proactive, "rule_id")
    migrator.rename_field(Proactive, "rule_name", "reason")
