use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[derive(DeriveIden)]
enum Categories {
    Table,
    Id,
    ParentId,
}

const FK_NAME: &str = "fk_categories_parent_id";

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.alter_table(
            Table::alter()
                .table(Categories::Table)
                .add_column(ColumnDef::new(Categories::ParentId).integer().null())
                .to_owned(),
        )
        .await?;

        m.create_foreign_key(
            ForeignKey::create()
                .name(FK_NAME)
                .from(Categories::Table, Categories::ParentId)
                .to(Categories::Table, Categories::Id)
                .on_delete(ForeignKeyAction::SetNull)
                .on_update(ForeignKeyAction::Cascade)
                .to_owned(),
        )
        .await
    }

    async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
        m.drop_foreign_key(
            ForeignKey::drop()
                .name(FK_NAME)
                .table(Categories::Table)
                .to_owned(),
        )
        .await?;

        m.alter_table(
            Table::alter()
                .table(Categories::Table)
                .drop_column(Categories::ParentId)
                .to_owned(),
        )
        .await
    }
}
