//! Trigram indexes so the admin order search stays fast as orders pile up.
//!
//! Order search is a plain substring (`ILIKE`) match over the high-signal,
//! free-text order fields — order number, email, customer/company name — run
//! through `f_unaccent` so diacritics and case never matter (see
//! `orders::Entity::search`). These `pg_trgm` GIN indexes let those `ILIKE`
//! lookups use an index instead of scanning every row. `pg_trgm` + `f_unaccent`
//! already exist from the product-search migration.

use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.get_connection()
            .execute_unprepared(
                r#"
                CREATE INDEX idx_orders_number_trgm
                    ON orders USING GIN (f_unaccent(order_number) gin_trgm_ops);
                CREATE INDEX idx_orders_email_trgm
                    ON orders USING GIN (f_unaccent(email) gin_trgm_ops);
                CREATE INDEX idx_orders_customer_name_trgm
                    ON orders USING GIN (f_unaccent(COALESCE(customer_name, '')) gin_trgm_ops);
                CREATE INDEX idx_orders_company_name_trgm
                    ON orders USING GIN (f_unaccent(COALESCE(company_name, '')) gin_trgm_ops);
                "#,
            )
            .await?;
        Ok(())
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.get_connection()
            .execute_unprepared(
                r#"
                DROP INDEX IF EXISTS idx_orders_company_name_trgm;
                DROP INDEX IF EXISTS idx_orders_customer_name_trgm;
                DROP INDEX IF EXISTS idx_orders_email_trgm;
                DROP INDEX IF EXISTS idx_orders_number_trgm;
                "#,
            )
            .await?;
        Ok(())
    }
}
