/*
 * authservice db/usersettings.rs
 * - pgsql usersettings functions
 *
 * Copyright (C) 2025 Real Microsoft, LLC
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use log::error;
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, IntoActiveModel};
use sea_orm::ActiveValue::Set;
use entity::user_settings;
use crate::db::user::{check_if_user_exists, FetchUserError};

#[derive(Debug, Clone)]
pub struct UserSettings {
    pub theme: String,
}

#[derive(Debug)]
pub enum FetchUserSettingsError {
    UserNotFound,
    DatabaseError,
}

pub async fn get_or_create_default_user_settings(db: &DatabaseConnection, user_id: String) -> Result<UserSettings, FetchUserSettingsError> {
    if let Some(us) = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
        error!("DATABASE ERROR WHILE FETCH USER SETTINGS: {e}");
        FetchUserSettingsError::DatabaseError
    })? {
        return Ok(UserSettings {
            theme: us.theme
        });
    }

    check_if_user_exists(db, user_id.clone()).await.map_err(|e| {
        match e {
            FetchUserError::UserNotFound => {FetchUserSettingsError::UserNotFound}
            FetchUserError::DatabaseError => {FetchUserSettingsError::DatabaseError}
        }
    })?;

    let us_record = user_settings::ActiveModel {
        user: Set(user_id),
        theme: Set("default".to_string()),
    };

    user_settings::Entity::insert(us_record).exec(db).await.map_err(|e| {
        error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
        FetchUserSettingsError::DatabaseError
    })?;

    Ok(UserSettings {
        theme: "default".to_string(),
    })
}

pub async fn set_theme(db: &DatabaseConnection, user_id: String, theme: String) -> Result<(), FetchUserSettingsError> {
    get_or_create_default_user_settings(db, user_id.clone()).await?;

    let mut us_record = user_settings::Entity::find_by_id(&user_id).one(db).await.map_err(|e| {
        error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
        FetchUserSettingsError::DatabaseError
    })?.ok_or(FetchUserSettingsError::UserNotFound)?.into_active_model();

    us_record.theme = Set(theme);

    us_record.update(db).await.map_err(|e| {
        error!("DATABASE ERROR WHILE INSERT USER_SETTINGS: {e}");
        FetchUserSettingsError::DatabaseError
    })?;

    Ok(())
}