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

/// 临时邮箱地址（用户创建，绑定 user，带过期与配额）
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "mailboxes")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    /// 所属用户 ID（FK users.id）
    pub user_id: String,
    /// 完整地址，如 abc123@mail.shenjianl.cn（唯一）
    #[sea_orm(unique)]
    pub address: String,
    /// 本地部分，如 abc123
    pub local_part: String,
    /// 域名，如 mail.shenjianl.cn
    pub domain: String,
    /// 邮箱级 access_token 的 SHA-256 哈希
    pub access_token_hash: String,
    /// 用途备注（可选）
    pub note: Option<String>,
    /// 状态：active | expired | revoked
    pub status: String,
    /// 单邮箱容量上限（字节）
    pub max_quota_bytes: i64,
    /// 已用容量（字节）
    pub used_bytes: i64,
    /// 邮箱过期时间
    pub expires_at: DateTime,
    pub created_at: DateTime,
    pub updated_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;
        let now = chrono::Utc::now().naive_utc();
        if insert {
            value.created_at = Set(now);
        }
        value.updated_at = Set(now);
        Ok(value)
    }
}
