use crate::domain::{dto::user::UpdateProfileRequest, entities::user_profiles};
use anyhow::Result;
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, Set, TryIntoModel};

pub struct UserProfileRepository {
    db: DatabaseConnection,
}
impl UserProfileRepository {
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }
    pub async fn get(&self, user_id: &str) -> Result<Option<user_profiles::Model>> {
        Ok(user_profiles::Entity::find_by_id(user_id)
            .one(&self.db)
            .await?)
    }
    pub async fn upsert(
        &self,
        user_id: String,
        input: UpdateProfileRequest,
    ) -> Result<user_profiles::Model> {
        let existing = self.get(&user_id).await?;
        let mut model = existing
            .map(Into::into)
            .unwrap_or_else(|| user_profiles::ActiveModel {
                user_id: Set(user_id),
                ..Default::default()
            });
        model.display_name = Set(input.display_name);
        model.avatar_url = Set(input.avatar_url);
        model.bio = Set(input.bio);
        Ok(model.save(&self.db).await?.try_into_model()?)
    }
    pub async fn delete(&self, user_id: &str) -> Result<()> {
        user_profiles::Entity::delete_by_id(user_id)
            .exec(&self.db)
            .await?;
        Ok(())
    }
}
