use crate::domain::entities::email_attachment;
use anyhow::Result;
use sea_orm::{
    ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, Set,
};

/// 邮件附件数据访问
pub struct AttachmentRepository {
    db: DatabaseConnection,
}

impl AttachmentRepository {
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }

    #[allow(dead_code)]
    pub async fn insert(
        &self,
        model: email_attachment::ActiveModel,
    ) -> Result<email_attachment::Model> {
        Ok(model.insert(&self.db).await?)
    }

    pub async fn find_by_id(&self, id: i64) -> Result<Option<email_attachment::Model>> {
        Ok(email_attachment::Entity::find_by_id(id)
            .one(&self.db)
            .await?)
    }

    pub async fn list_by_email(&self, email_id: i64) -> Result<Vec<email_attachment::Model>> {
        Ok(email_attachment::Entity::find()
            .filter(email_attachment::Column::EmailId.eq(email_id))
            .order_by_asc(email_attachment::Column::Id)
            .all(&self.db)
            .await?)
    }

    #[allow(dead_code)]
    pub async fn delete_by_email(&self, email_id: i64) -> Result<u64> {
        let res = email_attachment::Entity::delete_many()
            .filter(email_attachment::Column::EmailId.eq(email_id))
            .exec(&self.db)
            .await?;
        Ok(res.rows_affected)
    }

    /// 批量插入附件（收信时）
    #[allow(dead_code)]
    pub async fn insert_many(
        &self,
        email_id: i64,
        attachments: Vec<(Option<String>, String, i64, Vec<u8>)>,
    ) -> Result<()> {
        for (filename, content_type, size, content) in attachments {
            let model = email_attachment::ActiveModel {
                email_id: Set(email_id),
                filename: Set(filename),
                content_type: Set(content_type),
                size_bytes: Set(size),
                content: Set(Some(content)),
                ..Default::default()
            };
            model.insert(&self.db).await?;
        }
        Ok(())
    }
}
