package com.flightticket.util;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * JPA AttributeConverter for automatic encryption/decryption of String fields.
 * Apply this converter to entity fields that contain sensitive data.
 * 
 * Usage:
 * @Convert(converter = EncryptedStringConverter.class)
 * private String passportNumber;
 */
@Converter
@Component
public class EncryptedStringConverter implements AttributeConverter<String, String> {
    
    private static EncryptionUtil encryptionUtil;
    
    @Autowired
    public void setEncryptionUtil(EncryptionUtil encryptionUtil) {
        EncryptedStringConverter.encryptionUtil = encryptionUtil;
    }
    
    @Override
    public String convertToDatabaseColumn(String attribute) {
        if (encryptionUtil == null) {
            throw new IllegalStateException("EncryptionUtil not initialized");
        }
        return encryptionUtil.encrypt(attribute);
    }
    
    @Override
    public String convertToEntityAttribute(String dbData) {
        if (encryptionUtil == null) {
            throw new IllegalStateException("EncryptionUtil not initialized");
        }
        return encryptionUtil.decrypt(dbData);
    }
}
