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(ProcessDefinitions::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ProcessDefinitions::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::TenantId)
                            .uuid()
                            .not_null(),
                    )
                    .col(ColumnDef::new(ProcessDefinitions::Name).string().not_null())
                    .col(ColumnDef::new(ProcessDefinitions::Key).string().not_null())
                    .col(
                        ColumnDef::new(ProcessDefinitions::Version)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .col(ColumnDef::new(ProcessDefinitions::Category).string().null())
                    .col(
                        ColumnDef::new(ProcessDefinitions::Description)
                            .text()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::Nodes)
                            .json_binary()
                            .not_null()
                            .default(Expr::val("[]")),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::Edges)
                            .json_binary()
                            .not_null()
                            .default(Expr::val("[]")),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::Status)
                            .string()
                            .not_null()
                            .default("draft"),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::CreatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::UpdatedAt)
                            .timestamp_with_time_zone()
                            .not_null()
                            .default(Expr::current_timestamp()),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::CreatedBy)
                            .uuid()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::UpdatedBy)
                            .uuid()
                            .not_null(),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::DeletedAt)
                            .timestamp_with_time_zone()
                            .null(),
                    )
                    .col(
                        ColumnDef::new(ProcessDefinitions::VersionField)
                            .integer()
                            .not_null()
                            .default(1),
                    )
                    .to_owned(),
            )
            .await?;

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

        manager.get_connection().execute(sea_orm::Statement::from_string(
            sea_orm::DatabaseBackend::Postgres,
            "CREATE UNIQUE INDEX idx_process_definitions_key_version ON process_definitions (tenant_id, key, version) WHERE deleted_at IS 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(ProcessDefinitions::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum ProcessDefinitions {
    Table,
    Id,
    TenantId,
    Name,
    Key,
    Version,
    Category,
    Description,
    Nodes,
    Edges,
    Status,
    CreatedAt,
    UpdatedAt,
    CreatedBy,
    UpdatedBy,
    DeletedAt,
    VersionField,
}
