// Package secret encrypts sensitive settings values (passwords) at rest with
// AES-256-GCM, keyed by a PBKDF2 key derived from a user-chosen passphrase.
//
// The passphrase — not the machine — is the key source, so an encrypted
// database stays portable: copy the data folder to another PC, re-enter the
// passphrase there, and the secrets decrypt. Encryption is opt-in: until the
// user sets a passphrase, values are stored in clear (no behaviour change).
//
// Encrypted values are prefixed "enc:v1:" so reads can tell ciphertext from a
// legacy plaintext value and migrate transparently.
package secret

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/pbkdf2"
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"strings"
)

// Prefix marks an encrypted value. Bump the version if the scheme changes.
const Prefix = "enc:v1:"

// verifierPlaintext is encrypted under the key and stored so a wrong passphrase
// is detected on unlock (the decryption fails / mismatches) instead of silently
// producing garbage secrets.
const verifierPlaintext = "opslog-secret-verifier-v1"

// pbkdf2Iter is the work factor. ~600k SHA-256 rounds ≈ sub-second derivation,
// in line with current OWASP guidance for PBKDF2-HMAC-SHA256.
const pbkdf2Iter = 600_000

const keyLen = 32 // AES-256
const saltLen = 16

// NewSalt returns a fresh random salt to store alongside the verifier.
func NewSalt() ([]byte, error) {
	s := make([]byte, saltLen)
	if _, err := rand.Read(s); err != nil {
		return nil, err
	}
	return s, nil
}

// DeriveKey turns a passphrase + salt into the AES key.
func DeriveKey(passphrase string, salt []byte) ([]byte, error) {
	return pbkdf2.Key(sha256.New, passphrase, salt, pbkdf2Iter, keyLen)
}

// Cipher encrypts/decrypts individual values with the derived key.
type Cipher struct{ gcm cipher.AEAD }

// New builds a Cipher from a 32-byte key.
func New(key []byte) (*Cipher, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	return &Cipher{gcm: gcm}, nil
}

// Encrypt returns "enc:v1:<base64(nonce||ciphertext)>".
func (c *Cipher) Encrypt(plain string) string {
	nonce := make([]byte, c.gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return plain // extremely unlikely; never silently corrupt by returning bad data
	}
	ct := c.gcm.Seal(nonce, nonce, []byte(plain), nil)
	return Prefix + base64.StdEncoding.EncodeToString(ct)
}

// Decrypt reverses Encrypt. A value without the prefix is returned unchanged
// (legacy plaintext). A malformed/forged value returns an error.
func (c *Cipher) Decrypt(stored string) (string, error) {
	if !strings.HasPrefix(stored, Prefix) {
		return stored, nil
	}
	raw, err := base64.StdEncoding.DecodeString(stored[len(Prefix):])
	if err != nil {
		return "", err
	}
	ns := c.gcm.NonceSize()
	if len(raw) < ns {
		return "", errors.New("ciphertext too short")
	}
	pt, err := c.gcm.Open(nil, raw[:ns], raw[ns:], nil)
	if err != nil {
		return "", err
	}
	return string(pt), nil
}

// IsEncrypted reports whether a stored value is ciphertext.
func IsEncrypted(v string) bool { return strings.HasPrefix(v, Prefix) }

// MakeVerifier encrypts the known token so the passphrase can be validated later.
func (c *Cipher) MakeVerifier() string { return c.Encrypt(verifierPlaintext) }

// CheckVerifier returns true when c (derived from the entered passphrase)
// decrypts the stored verifier back to the known token — i.e. the passphrase is
// correct.
func (c *Cipher) CheckVerifier(stored string) bool {
	p, err := c.Decrypt(stored)
	if err != nil {
		return false
	}
	return subtle.ConstantTimeCompare([]byte(p), []byte(verifierPlaintext)) == 1
}
