import { Injectable } from '@nestjs/common';
import * as CryptoJS from 'crypto-js';

@Injectable()
export class CryptoService {
  private readonly secretKey = 'loTto_aPp-2026!';

  encrypt(text: string): string {
    const encrypted = CryptoJS.AES.encrypt(text, this.secretKey).toString();
    return this.base64UrlEncode(encrypted); // Evita problemas con URL
  }

  decrypt(encryptedText: string): string {
    const decoded = this.base64UrlDecode(encryptedText);
    const bytes = CryptoJS.AES.decrypt(decoded, this.secretKey);
    return bytes.toString(CryptoJS.enc.Utf8);
  }

  private base64UrlEncode(str: string): string {
    return Buffer.from(str, 'utf-8')
      .toString('base64')
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=+$/, ''); // Quita los "=" finales
  }

  private base64UrlDecode(str: string): string {
    str = str.replace(/-/g, '+').replace(/_/g, '/'); // Reemplaza "-" y "_"
    const pad = str.length % 4 === 0 ? '' : '='.repeat(4 - (str.length % 4));
    return Buffer.from(str + pad, 'base64').toString('utf-8');
  }

  cleanText(text: string): string {
    return text.replace(/[^a-zA-Z0-9áéíóúÁÉÍÓÚñÑ]/g, '');
  }
}
