// Package crypto provides application-layer encryption for sensitive data at
// rest (browser session storage, third-party API keys).
//
// Ciphertext format: "enc:v1:" + base64url(nonce || ciphertext||tag).
// Values without the prefix are treated as legacy plaintext and returned as-is
// on Decrypt, so enabling encryption is backward compatible with existing data.
package crypto

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

const cipherPrefix = "enc:v1:"

// Cipher encrypts/decrypts secret strings. When built without a key it is
// disabled and acts as a passthrough (for local dev), but Decrypt still
// transparently handles previously written ciphertext if any.
type Cipher struct {
	aead cipher.AEAD
}

// New builds a Cipher from a base64-encoded 32-byte (AES-256) key.
// An empty key returns a disabled (passthrough) cipher.
func New(base64Key string) (*Cipher, error) {
	base64Key = strings.TrimSpace(base64Key)
	if base64Key == "" {
		return &Cipher{}, nil
	}
	key, err := base64.StdEncoding.DecodeString(base64Key)
	if err != nil {
		return nil, fmt.Errorf("crypto: invalid base64 encryption key: %w", err)
	}
	if len(key) != 32 {
		return nil, fmt.Errorf("crypto: encryption key must be 32 bytes (got %d)", len(key))
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, fmt.Errorf("crypto: new cipher: %w", err)
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		return nil, fmt.Errorf("crypto: new gcm: %w", err)
	}
	return &Cipher{aead: aead}, nil
}

// Enabled reports whether a key is configured.
func (c *Cipher) Enabled() bool {
	return c != nil && c.aead != nil
}

// Encrypt returns ciphertext for non-empty plaintext when enabled; otherwise
// it returns the input unchanged.
func (c *Cipher) Encrypt(plaintext string) (string, error) {
	if !c.Enabled() || plaintext == "" {
		return plaintext, nil
	}
	if strings.HasPrefix(plaintext, cipherPrefix) {
		// Already encrypted; avoid double-encrypting.
		return plaintext, nil
	}
	nonce := make([]byte, c.aead.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return "", fmt.Errorf("crypto: read nonce: %w", err)
	}
	sealed := c.aead.Seal(nonce, nonce, []byte(plaintext), nil)
	return cipherPrefix + base64.RawURLEncoding.EncodeToString(sealed), nil
}

// Decrypt reverses Encrypt. Values without the cipher prefix are returned
// unchanged (legacy plaintext), keeping the change backward compatible.
func (c *Cipher) Decrypt(value string) (string, error) {
	if !strings.HasPrefix(value, cipherPrefix) {
		return value, nil
	}
	if !c.Enabled() {
		return "", errors.New("crypto: encrypted value found but no encryption key configured")
	}
	raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(value, cipherPrefix))
	if err != nil {
		return "", fmt.Errorf("crypto: decode ciphertext: %w", err)
	}
	nonceSize := c.aead.NonceSize()
	if len(raw) < nonceSize {
		return "", errors.New("crypto: ciphertext too short")
	}
	nonce, ct := raw[:nonceSize], raw[nonceSize:]
	plain, err := c.aead.Open(nil, nonce, ct, nil)
	if err != nil {
		return "", fmt.Errorf("crypto: decrypt: %w", err)
	}
	return string(plain), nil
}
