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> {
        // Add the `state` column to `tickets`: Open or Closed, defaults to Open.
        // This replaces the old system where "open" and "closed" were labels.
        manager
            .get_connection()
            .execute_unprepared(
                "ALTER TABLE tickets ADD COLUMN state varchar(16) NOT NULL DEFAULT 'open'",
            )
            .await?;

        // Index for filtering by state within a repository
        manager
            .get_connection()
            .execute_unprepared(
                "CREATE INDEX IF NOT EXISTS idx_tickets_repository_state \
                 ON tickets (repository_id, state)",
            )
            .await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .get_connection()
            .execute_unprepared("DROP INDEX IF EXISTS idx_tickets_repository_state")
            .await?;

        manager
            .get_connection()
            .execute_unprepared("ALTER TABLE tickets DROP COLUMN IF EXISTS state")
            .await?;

        Ok(())
    }
}
