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", "ai_image_provider")
            .await?
        {
            manager
                .alter_table(
                    Table::alter()
                        .table(table.clone())
                        .add_column(
                            ColumnDef::new(Alias::new("ai_image_provider"))
                                .string()
                                .null(),
                        )
                        .to_owned(),
                )
                .await?;
        }

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

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

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

        Ok(())
    }

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

        for column in [
            "ai_image_model",
            "ai_image_api_key",
            "ai_image_api_base",
            "ai_image_provider",
        ] {
            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(())
    }
}
