from peewee import CompositeKey, Model, CharField, IntegerField


def migrate(migrator, *_, fake=False, **__):
    if fake:
        return

    icontact_throttle = migrator.orm["icontact_throttle"]

    class TmpIContactThrottle(Model):
        class Meta:
            db_table = "tmp_icontact_throttle"
            primary_key = CompositeKey("message_type", "user")

        message_type = CharField()
        user = CharField(null=True)
        timestamp = IntegerField(default=0)

    migrator.add_fields(
        icontact_throttle,
        user=CharField(null=True),
    )

    # change the primary key
    migrator.create_model(TmpIContactThrottle)
    migrator.sql(
        "INSERT INTO tmp_icontact_throttle (message_type, user, timestamp) "
        "SELECT message_type, user, timestamp FROM icontact_throttle"
    )
    migrator.sql("DROP TABLE icontact_throttle")
    migrator.sql(
        "ALTER TABLE tmp_icontact_throttle RENAME TO icontact_throttle",
    )


def rollback(migrator, *_, fake=False, **__):
    if fake:
        return

    class TmpIContactThrottle(Model):
        class Meta:
            db_table = "icontact_throttle"

        message_type = CharField(primary_key=True)
        timestamp = IntegerField(default=0)

    migrator.create_model(TmpIContactThrottle)
    migrator.sql(
        "INSERT INTO tmp_icontact_throttle (message_type, timestamp) "
        "SELECT message_type, timestamp FROM icontact_throttle"
    )
    migrator.sql("DROP TABLE icontact_throttle")
    migrator.sql(
        "ALTER TABLE tmp_icontact_throttle RENAME TO icontact_throttle",
    )
