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,
            "content_events",
            &[
                ("id", ColType::PkAuto),
                ("event_type", ColType::String),
                ("path", ColType::String),
                ("post_slug", ColType::StringNull),
                ("session_id", ColType::StringNull),
                ("referrer", ColType::StringNull),
                ("user_agent", ColType::TextNull),
                ("duration_ms", ColType::IntegerNull),
                ("progress_percent", ColType::IntegerNull),
                ("metadata", ColType::JsonBinaryNull),
            ],
            &[],
        )
        .await?;

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

        manager
            .create_index(
                Index::create()
                    .name("idx_content_events_post_slug_created_at")
                    .table(Alias::new("content_events"))
                    .col(Alias::new("post_slug"))
                    .col(Alias::new("created_at"))
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_content_events_referrer")
                    .table(Alias::new("content_events"))
                    .col(Alias::new("referrer"))
                    .to_owned(),
            )
            .await?;

        Ok(())
    }

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

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