import { HttpException, HttpStatus, Inject, Injectable, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as crypto from 'crypto';
import { Settings, SettingType } from 'src/entities/settings.entity';
import { Repository } from 'typeorm';
import { ExceptionHandler } from 'winston';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
@Injectable()
export class EncryptionService implements OnModuleInit {
    private readonly algorithm = 'aes-256-cbc';
    private secretKey = "";
    private readonly iv = crypto.randomBytes(16); // IV should be stored securely
    constructor(
        @Inject(CACHE_MANAGER) private cacheManager: Cache,
        @InjectRepository(Settings)
        private Settings: Repository<Settings>,
    ) { }
    async onModuleInit() {
        this.secretKey = await this.cacheManager.get('secretKey');
        if (!this.secretKey) {
            this.secretKey = (await this.Settings.findOne({ where: { type: SettingType.ENCRYPTION } })).value
            this.cacheManager.set('secretKey', this.secretKey)
            console.log("SSSSSSSS", this.secretKey)
        }
    }

    /**
     * Encrypts a given text using AES-256-CBC
     * @param text The text to encrypt
     * @returns Encrypted text in base64 format
     */
    async encrypt(text: string) {
        const cipher = crypto.createCipheriv(this.algorithm, Buffer.from(this.secretKey, 'utf-8'), this.iv);
        let encrypted = cipher.update(text, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return `${this.iv.toString('hex')}:${encrypted}`;
    }

    /**
     * Decrypts a given encrypted text
     * @param encryptedText The text to decrypt
     * @returns Decrypted original text
     */
    async decrypt(encryptedText: string) {
        try {
            console.log("DDDDDD", this.secretKey)
            const [ivHex, encrypted] = encryptedText.split(':');
            const iv = Buffer.from(ivHex, 'hex');
            const decipher = crypto.createDecipheriv(this.algorithm, Buffer.from(this.secretKey, 'utf-8'), iv);
            let decrypted = decipher.update(encrypted, 'hex', 'utf8');
            decrypted += decipher.final('utf8');
            return decrypted;
        } catch (e) {
            console.log(e)
            throw new HttpException(e.message, HttpStatus.BAD_REQUEST);
        }

    }
}
