use crate::feed_api::error::{FeedApiError, FeedApiErrorKind};
use log::error;
use magic_crypt::{new_magic_crypt, MagicCryptTrait};
use serde_derive::{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) -> Result<String, FeedApiError> {
        let key : String = PasswordCryptKey::get();
        let crypt = new_magic_crypt!(key, 256);
        Ok(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!("Failed to decrypt password: {}", password);
            FeedApiErrorKind::Encryption
        })?;
        Ok(password)
    }
}
