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> {
        manager
            .create_table(
                Table::create()
                    .table(Organizations::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Organizations::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Organizations::TenantId).uuid().not_null())
                    .col(ColumnDef::new(Organizations::Name).string().not_null())
                    .col(ColumnDef::new(Organizations::Code).string().null())
                    .col(ColumnDef::new(Organizations::ParentId).uuid().null())
                    .col(ColumnDef::new(Organizations::Path).string().null())
                    .col(
                        ColumnDef::new(Organizations::Level)
                            .integer()
                            .not_null()
                            .default(0),
                    )
                    .col(
                        ColumnDef::new(Organizations::SortOrder)
                            .integer()
                            .not_null()
                            .default(0),
                    )
                    .col(
                        ColumnDef::new(Organizations::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(Organizations::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(ColumnDef::new(Organizations::CreatedBy).uuid().not_null())
                    .col(ColumnDef::new(Organizations::UpdatedBy).uuid().not_null())
                    .col(
                        ColumnDef::new(Organizations::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(Organizations::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .foreign_key(
                        &mut ForeignKey::create()
                            .name("fk_organizations_parent_id")
                            .from(Organizations::Table, Organizations::ParentId)
                            .to(Organizations::Table, Organizations::Id)
                            .on_delete(ForeignKeyAction::Restrict)
                            .to_owned(),
                    )
                    .to_owned(),
            )
            .await?;

        manager
            .create_index(
                Index::create()
                    .name("idx_organizations_tenant_id")
                    .table(Organizations::Table)
                    .col(Organizations::TenantId)
                    .to_owned(),
            )
            .await?;

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_organizations_tenant_code ON organizations (tenant_id, code) WHERE code IS NOT NULL".to_string(),
        )).await.map_err(|e| DbErr::Custom(e.to_string()))?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(Organizations::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum Organizations {
    Table,
    Id,
    TenantId,
    Name,
    Code,
    ParentId,
    Path,
    Level,
    SortOrder,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    Version,
}
