use sea_orm::entity::prelude::*;
use sea_orm::Set;
use serde::{Deserialize, Serialize};

/// 积分流水（append-only，balance_after 保证可审计）
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "credit_transactions")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub user_id: String,
    /// 正=充值/赠送，负=消费
    pub delta: i64,
    /// 变更后余额（审计关键）
    pub balance_after: i64,
    /// register_bonus | create_mailbox | receive_email | admin_adjust | ...
    pub reason: String,
    pub related_mailbox_id: Option<i64>,
    pub related_email_id: Option<i64>,
    pub description: Option<String>,
    pub operator_id: Option<String>,
    pub created_at: DateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, _: &C, insert: bool) -> Result<Self, DbErr> {
        let mut value = self;
        if insert {
            value.created_at = Set(chrono::Utc::now().naive_utc());
        }
        Ok(value)
    }
}
