package common

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
)

func ParsePublicKeyFromPEM(pubPEM []byte) (*rsa.PublicKey, error) {
	block, _ := pem.Decode(pubPEM)
	if block == nil {
		return nil, errors.New("PEM data decoding failed, possibly due to incorrect format")
	}

	var pubKey *rsa.PublicKey
	var err error

	switch block.Type {
	case "PUBLIC KEY":
		// PKIX format (SubjectPublicKeyInfo)
		pubInterface, parseErr := x509.ParsePKIXPublicKey(block.Bytes)
		if parseErr != nil {
			return nil, fmt.Errorf("failed to parse PKIX public key: %w", parseErr)
		}
		var ok bool
		pubKey, ok = pubInterface.(*rsa.PublicKey)
		if !ok {
			return nil, errors.New("parsed key is not an RSA public key")
		}
	case "RSA PUBLIC KEY":
		// PKCS#1 format
		pubKey, err = x509.ParsePKCS1PublicKey(block.Bytes)
		if err != nil {
			// Some keys have "RSA PUBLIC KEY" header but contain PKIX format
			// Try PKIX as fallback
			pubInterface, parseErr := x509.ParsePKIXPublicKey(block.Bytes)
			if parseErr != nil {
				return nil, fmt.Errorf("failed to parse public key as both PKCS#1 and PKIX: %w", errors.Join(err, parseErr))
			}
			var ok bool
			pubKey, ok = pubInterface.(*rsa.PublicKey)
			if !ok {
				return nil, errors.New("parsed key is not an RSA public key")
			}
		}
	default:
		return nil, fmt.Errorf("incorrect PEM block type: %s", block.Type)
	}

	return pubKey, nil
}

func EncryptWithPublicKey(pubKey *rsa.PublicKey, data []byte) ([]byte, error) {
	encryptedData, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, data, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to encrypt data: %w", err)
	}
	return encryptedData, nil
}
