import crypto from 'crypto';

if (!process.env.PII_ENCRYPTION_KEY) {
  throw new Error("PII_ENCRYPTION_KEY environment variable is required — set it before starting the server");
}
const ENCRYPTION_KEY = process.env.PII_ENCRYPTION_KEY;
const IV_LENGTH = 16;

export class FieldEncryptionService {
  static encrypt(text: string): string {
    const iv = crypto.randomBytes(IV_LENGTH);
    const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    
    let encrypted = cipher.update(text, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    
    return `${iv.toString('base64')}:${encrypted}`;
  }

  static decrypt(encryptedText: string): string {
    const [ivBase64, ciphertext] = encryptedText.split(':');
    const iv = Buffer.from(ivBase64, 'base64');
    const key = crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    
    let decrypted = decipher.update(ciphertext, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    
    return decrypted;
  }

  static hashPhoneNumber(phoneNumber: string): string {
    return crypto.createHash('sha256').update(phoneNumber).digest('hex');
  }
}
