use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

const TABLE: &str = "comments";
const IP_ADDRESS_COLUMN: &str = "ip_address";
const USER_AGENT_COLUMN: &str = "user_agent";
const REFERER_COLUMN: &str = "referer";
const COMMENT_IP_INDEX: &str = "idx_comments_ip_address";

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let table = Alias::new(TABLE);

        if !manager.has_column(TABLE, IP_ADDRESS_COLUMN).await? {
            manager
                .alter_table(
                    Table::alter()
                        .table(table.clone())
                        .add_column(
                            ColumnDef::new(Alias::new(IP_ADDRESS_COLUMN))
                                .string()
                                .null(),
                        )
                        .to_owned(),
                )
                .await?;
        }

        if !manager.has_column(TABLE, USER_AGENT_COLUMN).await? {
            manager
                .alter_table(
                    Table::alter()
                        .table(table.clone())
                        .add_column(ColumnDef::new(Alias::new(USER_AGENT_COLUMN)).text().null())
                        .to_owned(),
                )
                .await?;
        }

        if !manager.has_column(TABLE, REFERER_COLUMN).await? {
            manager
                .alter_table(
                    Table::alter()
                        .table(table)
                        .add_column(ColumnDef::new(Alias::new(REFERER_COLUMN)).text().null())
                        .to_owned(),
                )
                .await?;
        }

        manager
            .get_connection()
            .execute_unprepared(&format!(
                "CREATE INDEX IF NOT EXISTS {COMMENT_IP_INDEX} ON {TABLE} ({IP_ADDRESS_COLUMN})"
            ))
            .await?;

        Ok(())
    }

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

        for column in [REFERER_COLUMN, USER_AGENT_COLUMN, IP_ADDRESS_COLUMN] {
            if manager.has_column(TABLE, column).await? {
                manager
                    .alter_table(
                        Table::alter()
                            .table(Alias::new(TABLE))
                            .drop_column(Alias::new(column))
                            .to_owned(),
                    )
                    .await?;
            }
        }

        Ok(())
    }
}
