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#"
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" DROP DEFAULT;
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" TYPE "notification_type_enum"[] USING '{}'::notification_type_enum[];
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" SET DEFAULT '{}'::notification_type_enum[];
            DROP TYPE user_profile_mutingnotificationtypes_enum;
            "#,
        )
        .await?;

        Ok(())
    }

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

        db.execute_unprepared(
            r#"
            CREATE TYPE user_profile_mutingnotificationtypes_enum AS ENUM ('follow', 'mention', 'reply', 'renote', 'quote', 'reaction', 'pollVote', 'pollEnded', 'receiveFollowRequest', 'followRequestAccepted', 'groupInvited', 'app');
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" DROP DEFAULT;
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" TYPE "user_profile_mutingnotificationtypes_enum"[] USING '{}'::user_profile_mutingnotificationtypes_enum[];
            ALTER TABLE "user_profile" ALTER COLUMN "mutingNotificationTypes" SET DEFAULT '{}'::user_profile_mutingnotificationtypes_enum[];
            "#,
        )
        .await?;

        txn.commit().await?;

        Ok(())
    }
}
