package zcrypt

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
)

func Encrypt(plaintext string, key []byte) (string, error) {
	// Create a new AES cipher

	c, err := aes.NewCipher(key)

	if err != nil {
		return "", err
	}

	// Generate a random nonce
	nonce := make([]byte, 12)
	if _, err := rand.Read(nonce); err != nil {
		return "", err
	}

	// Create a GCM cipher
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return "", err
	}

	// Encrypt the plaintext
	ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)

	// Encode the ciphertext to base64
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func Decrypt(ciphertext string, key []byte) (string, error) {
	// Decode the ciphertext from base64
	ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}

	// Create a new AES cipher
	c, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}

	// Create a GCM cipher
	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return "", err
	}

	// Decrypt the ciphertext
	nonce := ciphertextBytes[:12]
	plaintext, err := gcm.Open(nil, nonce, ciphertextBytes[12:], nil)
	if err != nil {
		return "", err
	}

	return string(plaintext), nil
}

func GenerateAESKey() []byte {
	// AES requires a 16-byte (128-bit) key
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		fmt.Println("error generating AES key: %w", err)
		return nil
	}
	return key
}
