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

/// 灰名单条目（triplet：sender_ip + mail_from + rcpt_to）
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "greylist_entries")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub sender_ip: String,
    pub mail_from: String,
    pub rcpt_to: String,
    pub first_seen: DateTime,
    /// 期望重试时间（首次 + retry_delay）
    pub retry_after: DateTime,
    pub delivered: bool,
    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;
        let now = chrono::Utc::now().naive_utc();
        if insert {
            value.created_at = Set(now);
            value.first_seen = Set(now);
        }
        Ok(value)
    }
}
