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");

        if !manager
            .has_column("site_settings", "maintenance_mode_enabled")
            .await?
        {
            manager
                .alter_table(
                    Table::alter()
                        .table(table.clone())
                        .add_column(
                            ColumnDef::new(Alias::new("maintenance_mode_enabled"))
                                .boolean()
                                .null()
                                .default(false),
                        )
                        .to_owned(),
                )
                .await?;
        }

        if !manager
            .has_column("site_settings", "maintenance_access_code")
            .await?
        {
            manager
                .alter_table(
                    Table::alter()
                        .table(table)
                        .add_column(
                            ColumnDef::new(Alias::new("maintenance_access_code"))
                                .text()
                                .null(),
                        )
                        .to_owned(),
                )
                .await?;
        }

        Ok(())
    }

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

        if manager
            .has_column("site_settings", "maintenance_access_code")
            .await?
        {
            manager
                .alter_table(
                    Table::alter()
                        .table(table.clone())
                        .drop_column(Alias::new("maintenance_access_code"))
                        .to_owned(),
                )
                .await?;
        }

        if manager
            .has_column("site_settings", "maintenance_mode_enabled")
            .await?
        {
            manager
                .alter_table(
                    Table::alter()
                        .table(table)
                        .drop_column(Alias::new("maintenance_mode_enabled"))
                        .to_owned(),
                )
                .await?;
        }

        Ok(())
    }
}
