use sea_orm_migration::prelude::*;
use sea_orm_migration::sea_orm::DbBackend;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        if manager.get_database_backend() != DbBackend::Postgres {
            return Ok(());
        }

        manager
            .get_connection()
            .execute_unprepared(
                r#"
                CREATE INDEX IF NOT EXISTS idx_posts_search_fts
                ON posts
                USING GIN (
                    (
                        setweight(to_tsvector('simple', coalesce(title, '')), 'A') ||
                        setweight(to_tsvector('simple', coalesce(description, '')), 'B') ||
                        setweight(to_tsvector('simple', coalesce(category, '')), 'C') ||
                        setweight(to_tsvector('simple', coalesce(tags::text, '')), 'C') ||
                        setweight(to_tsvector('simple', coalesce(content, '')), 'D')
                    )
                );
                "#,
            )
            .await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        if manager.get_database_backend() != DbBackend::Postgres {
            return Ok(());
        }

        manager
            .get_connection()
            .execute_unprepared("DROP INDEX IF EXISTS idx_posts_search_fts;")
            .await?;
        Ok(())
    }
}
