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)
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("turnstile_site_key"))
                            .text()
                            .null(),
                    )
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("turnstile_secret_key"))
                            .text()
                            .null(),
                    )
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("web_push_vapid_public_key"))
                            .text()
                            .null(),
                    )
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("web_push_vapid_private_key"))
                            .text()
                            .null(),
                    )
                    .add_column_if_not_exists(
                        ColumnDef::new(Alias::new("web_push_vapid_subject"))
                            .text()
                            .null(),
                    )
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

        for column in [
            "web_push_vapid_subject",
            "web_push_vapid_private_key",
            "web_push_vapid_public_key",
            "turnstile_secret_key",
            "turnstile_site_key",
        ] {
            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(())
    }
}
