use crate::feed_api::error::FeedApiError;
use magic_crypt::{MagicCryptTrait, new_magic_crypt};
use serde::{Deserialize, Serialize};
use std::str;

include!(concat!(env!("OUT_DIR"), "/password_crypt_key.rs"));

#[derive(Debug, Serialize, Deserialize)]
pub struct PasswordEncryption {
    password_crypt_key: String,
}

impl PasswordEncryption {
    pub fn encrypt(password: &str) -> String {
        let key: String = PasswordCryptKey::get();
        let crypt = new_magic_crypt!(key, 256);
        crypt.encrypt_str_to_base64(password)
    }

    pub fn decrypt(password: &str) -> Result<String, FeedApiError> {
        let key: String = PasswordCryptKey::get();
        let crypt = new_magic_crypt!(key, 256);
        let password = crypt.decrypt_base64_to_string(password).map_err(|error| {
            tracing::error!(%password, %error, "Failed to decrypt password");
            FeedApiError::Encryption
        })?;
        Ok(password)
    }
}
