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 posts_table = Alias::new("posts");
        let site_settings_table = Alias::new("site_settings");

        if !manager.has_column("posts", "images").await? {
            manager
                .alter_table(
                    Table::alter()
                        .table(posts_table.clone())
                        .add_column(ColumnDef::new(Alias::new("images")).json_binary().null())
                        .to_owned(),
                )
                .await?;
        }

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

        Ok(())
    }

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

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

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

        Ok(())
    }
}
