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

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

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

        manager
            .get_connection()
            .execute(Statement::from_string(
                DbBackend::Postgres,
                r#"
                UPDATE site_settings
                SET
                    ai_providers = jsonb_build_array(
                        jsonb_strip_nulls(
                            jsonb_build_object(
                                'id', 'default',
                                'name', COALESCE(NULLIF(trim(ai_provider), ''), '默认提供商'),
                                'provider', COALESCE(NULLIF(trim(ai_provider), ''), 'newapi'),
                                'api_base', NULLIF(trim(ai_api_base), ''),
                                'api_key', NULLIF(trim(ai_api_key), ''),
                                'chat_model', NULLIF(trim(ai_chat_model), '')
                            )
                        )
                    ),
                    ai_active_provider_id = COALESCE(NULLIF(trim(ai_active_provider_id), ''), 'default')
                WHERE ai_providers IS NULL
                  AND (
                    COALESCE(trim(ai_provider), '') <> ''
                    OR COALESCE(trim(ai_api_base), '') <> ''
                    OR COALESCE(trim(ai_api_key), '') <> ''
                    OR COALESCE(trim(ai_chat_model), '') <> ''
                  )
                "#
                .to_string(),
            ))
            .await?;

        Ok(())
    }

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

        for column in ["ai_active_provider_id", "ai_providers"] {
            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(())
    }
}
