//! `SeaORM` Entity, @generated by sea-orm-codegen

use schemars::JsonSchema;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

/// 租户成员状态（1: 正常, 2: 禁用, 3: 移除）
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    EnumIter,
    DeriveActiveEnum,
    Serialize_repr,
    Deserialize_repr,
    JsonSchema,
)]
#[sea_orm(rs_type = "i16", db_type = "SmallInteger")]
#[repr(i16)]
pub enum TenantMembershipStatus {
    /// 正常
    #[sea_orm(num_value = 1)]
    Enabled = 1,
    /// 禁用
    #[sea_orm(num_value = 2)]
    Disabled = 2,
    /// 移除
    #[sea_orm(num_value = 3)]
    Removed = 3,
}

/// 租户成员来源
#[derive(
    Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
#[sea_orm(rs_type = "String", db_type = "String(StringLen::N(32))")]
pub enum TenantMembershipSource {
    /// 手动
    #[sea_orm(string_value = "manual")]
    Manual,
    /// 邀请
    #[sea_orm(string_value = "invite")]
    Invite,
    /// 单点登录
    #[sea_orm(string_value = "sso")]
    Sso,
    /// SCIM
    #[sea_orm(string_value = "scim")]
    Scim,
    /// 系统初始化
    #[sea_orm(string_value = "system")]
    System,
}

#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(schema_name = "tenant", table_name = "tenant_membership")]
pub struct Model {
    /// 主键 ID
    #[sea_orm(primary_key)]
    pub id: i64,
    /// 租户业务唯一标识
    #[sea_orm(unique_key = "uk_tenant_tenant_membership_tenant_user")]
    pub tenant_id: String,
    /// 用户 ID
    pub user_id: i64,
    /// 租户角色编码
    pub role_code: String,
    /// 是否默认租户
    pub is_default: bool,
    /// 成员状态
    pub status: TenantMembershipStatus,
    /// 来源
    pub source: TenantMembershipSource,
    /// 加入时间
    pub joined_time: DateTime,
    /// 最近访问时间
    pub last_access_time: Option<DateTime>,
    /// 备注
    pub remark: String,
    /// 创建人
    pub create_by: String,
    /// 创建时间
    pub create_time: DateTime,
    /// 更新人
    pub update_by: String,
    /// 更新时间
    pub update_time: DateTime,
}

#[sea_orm::entity::prelude::async_trait::async_trait]
impl sea_orm::ActiveModelBehavior for self::ActiveModel {
    async fn before_save<C>(mut self, _db: &C, insert: bool) -> Result<Self, sea_orm::DbErr>
    where
        C: sea_orm::ConnectionTrait,
    {
        let now = chrono::Local::now().naive_local();
        self.update_time = sea_orm::Set(now);
        if insert {
            self.create_time = sea_orm::Set(now);
        }
        Ok(self)
    }
}
