use loco_rs::schema::*;
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> {
        create_table(
            manager,
            "query_events",
            &[
                ("id", ColType::PkAuto),
                ("event_type", ColType::String),
                ("query_text", ColType::Text),
                ("normalized_query", ColType::Text),
                ("request_path", ColType::StringNull),
                ("referrer", ColType::StringNull),
                ("user_agent", ColType::TextNull),
                ("result_count", ColType::IntegerNull),
                ("success", ColType::BooleanNull),
                ("response_mode", ColType::StringNull),
                ("provider", ColType::StringNull),
                ("chat_model", ColType::StringNull),
                ("latency_ms", ColType::IntegerNull),
            ],
            &[],
        )
        .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_query_events_event_type_created_at")
                    .table(Alias::new("query_events"))
                    .col(Alias::new("event_type"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_query_events_normalized_query")
                    .table(Alias::new("query_events"))
                    .col(Alias::new("normalized_query"))
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        for index_name in [
            "idx_query_events_normalized_query",
            "idx_query_events_event_type_created_at",
        ] {
            manager
                .drop_index(
                    Index::drop()
                        .name(index_name)
                        .table(Alias::new("query_events"))
                        .to_owned(),
                )
                .await?;
        }

        drop_table(manager, "query_events").await
    }
}
