use sea_orm_migration::prelude::*;
use sea_orm_migration::sea_orm::TransactionTrait;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let db = manager.get_connection();

        db.execute_unprepared(
            r#"
            DELETE FROM "notification" WHERE "type" = 'pollVote' OR "type" = 'groupInvited';

            ALTER TYPE "notification_type_enum" RENAME TO "notification_type_enum_old";
            CREATE TYPE "notification_type_enum" AS ENUM('follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollEnded', 'receiveFollowRequest', 'followRequestAccepted', 'app');
            ALTER TABLE "notification" ALTER COLUMN "type" TYPE "notification_type_enum" USING "type"::text::notification_type_enum;
            DROP TYPE "notification_type_enum_old";
            "#,
        )
        .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let db = manager.get_connection();
        let txn = db.begin().await?;

        db.execute_unprepared(
            r#"
            ALTER TYPE "notification_type_enum" RENAME TO "notification_type_enum_old";
            CREATE TYPE "notification_type_enum" AS ENUM('follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'pollEnded', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited', 'app');
            ALTER TABLE "notification" ALTER COLUMN "type" TYPE "notification_type_enum" USING "type"::text::notification_type_enum;
            DROP TYPE "notification_type_enum_old";
            "#,
        )
        .await?;

        txn.commit().await?;

        Ok(())
    }
}
