//! Create organization_members table.

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(OrganizationMembers::Table)
                    .if_not_exists()
                    .col(ColumnDef::new(OrganizationMembers::OrganizationId).string().not_null())
                    .col(ColumnDef::new(OrganizationMembers::UserId).uuid().not_null())
                    .col(ColumnDef::new(OrganizationMembers::Role).string().not_null())
                    .col(ColumnDef::new(OrganizationMembers::JoinedAt).big_integer().not_null())
                    .primary_key(
                        Index::create()
                            .col(OrganizationMembers::OrganizationId)
                            .col(OrganizationMembers::UserId),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .from(OrganizationMembers::Table, OrganizationMembers::OrganizationId)
                            .to(super::m005_create_organizations::Organizations::Table, super::m005_create_organizations::Organizations::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .from(OrganizationMembers::Table, OrganizationMembers::UserId)
                            .to(super::m001_create_users::Users::Table, super::m001_create_users::Users::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .to_owned(),
            )
            .await
    }

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

#[derive(DeriveIden)]
enum OrganizationMembers {
    Table,
    OrganizationId,
    UserId,
    Role,
    JoinedAt,
}
