package helper

import (
	"log"

	lzstring "github.com/daku10/go-lz-string"
)

// StringDecrypt - langsung coba decompress tanpa decrypt ulang
func StringDecrypt(key string, encryptedString string) (string, error) {
	log.Printf("StringDecrypt: Attempting decompression, data length: %d", len(encryptedString))

	// Method 1: Try direct LZ-string decompression (data sudah didecrypt di response.go)
	if result, err := lzstring.DecompressFromEncodedURIComponent(encryptedString); err == nil && len(result) > 0 {
		log.Printf("StringDecrypt: Direct decompression successful")
		return result, nil
	}

	// Method 2: Try other LZ-string methods
	if result, err := lzstring.DecompressFromBase64(encryptedString); err == nil && len(result) > 0 {
		log.Printf("StringDecrypt: Base64 decompression successful")
		return result, nil
	}

	// Method 3: If all fail, return the original string
	log.Printf("StringDecrypt: All decompression failed, returning original data")
	return encryptedString, nil
}

func RemovePKCS7Padding(data []byte) []byte {
	if len(data) == 0 {
		return data
	}

	paddingLength := int(data[len(data)-1])
	if paddingLength > len(data) || paddingLength == 0 {
		log.Printf("RemovePKCS7Padding: Invalid padding length: %d, data length: %d", paddingLength, len(data))
		return data // Return original data if padding is invalid
	}

	// Verify all padding bytes are correct
	for i := len(data) - paddingLength; i < len(data); i++ {
		if data[i] != byte(paddingLength) {
			log.Printf("RemovePKCS7Padding: Invalid padding byte at position %d", i)
			return data // Return original data if padding is invalid
		}
	}

	return data[:len(data)-paddingLength]
}
