use crate::domain::entities::email_logs;
use anyhow::Result;
use sea_orm::{
    ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, Set,
};
pub struct EmailLogRepository {
    db: DatabaseConnection,
}
impl EmailLogRepository {
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }
    pub async fn add(
        &self,
        user_id: Option<String>,
        recipient: String,
        status: String,
        error: Option<String>,
    ) -> Result<()> {
        email_logs::ActiveModel {
            user_id: Set(user_id),
            recipient: Set(recipient),
            kind: Set("verification".into()),
            status: Set(status),
            error: Set(error),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(())
    }
    pub async fn latest(&self, user_id: &str) -> Result<Option<email_logs::Model>> {
        Ok(email_logs::Entity::find()
            .filter(email_logs::Column::UserId.eq(user_id))
            .order_by_desc(email_logs::Column::CreatedAt)
            .one(&self.db)
            .await?)
    }
}
