use sea_orm::{DbBackend, Statement};
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let table = Alias::new("site_settings");

        manager
            .alter_table(
                Table::alter()
                    .table(table.clone())
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("comment_verification_mode"))
                            .string()
                            .null(),
                    )
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("subscription_verification_mode"))
                            .string()
                            .null(),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DbBackend::Postgres,
                r#"
                UPDATE site_settings
                SET comment_verification_mode = CASE
                    WHEN COALESCE(comment_turnstile_enabled, false) THEN 'turnstile'
                    ELSE 'captcha'
                END
                WHERE COALESCE(trim(comment_verification_mode), '') = ''
                "#
                .to_string(),
            ))
            .await?;

        manager
            .get_connection()
            .execute(Statement::from_string(
                DbBackend::Postgres,
                r#"
                UPDATE site_settings
                SET subscription_verification_mode = CASE
                    WHEN COALESCE(subscription_turnstile_enabled, false) THEN 'turnstile'
                    ELSE 'off'
                END
                WHERE COALESCE(trim(subscription_verification_mode), '') = ''
                "#
                .to_string(),
            ))
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let table = Alias::new("site_settings");

        for column in [
            "subscription_verification_mode",
            "comment_verification_mode",
        ] {
            if manager.has_column("site_settings", column).await? {
                manager
                    .alter_table(
                        Table::alter()
                            .table(table.clone())
                            .drop_column(Alias::new(column))
                            .to_owned(),
                    )
                    .await?;
            }
        }

        Ok(())
    }
}
