// Package crypto provides AES-256-GCM symmetric encryption for sensitive
// secret fields persisted to the database (e.g. git credentials, LLM API keys).
//
// The master key is supplied by the caller (see config.MasterKey) and never
// stored alongside the ciphertext.
//
// As of the secret-hardening epic, the underlying engine is KeyedEncryptor:
// every blob is sealed under a key *version* whose number is persisted in a
// per-row key_version column (the key material stays in env/KMS). The legacy
// Encryptor type below is a thin version-1 shim so the ~30 existing call sites
// — which neither know nor care about versions — compile and behave unchanged.
package crypto

import (
	"context"
	"fmt"
)

// Encryptor 用 AES-256-GCM 加解密 secret（version-1 shim over KeyedEncryptor）。
// 密文格式：nonce(12) || ciphertext || tag（与历史一致，未变）。
type Encryptor struct {
	keyed   *KeyedEncryptor
	version int
}

// NewEncryptor constructs an Encryptor from a 32-byte (AES-256) key.
// Any other key length yields an error rather than silently downgrading.
// It builds a KeyedEncryptor backed by an EnvProvider seeded with this key at
// version 1 and a static version-1 store, preserving the previous semantics.
func NewEncryptor(key []byte) (*Encryptor, error) {
	if len(key) != 32 {
		return nil, fmt.Errorf("key must be 32 bytes (got %d)", len(key))
	}
	keyed := NewKeyedEncryptor(NewEnvProvider(key), NewStaticKeyStore(1))
	// Eagerly validate the key by building the v1 AEAD once.
	if _, err := keyed.gcmFor(context.Background(), 1); err != nil {
		return nil, err
	}
	return &Encryptor{keyed: keyed, version: 1}, nil
}

// NewEncryptorFromKeyed wraps an existing KeyedEncryptor as a fixed-version
// Encryptor shim. version is the version this shim seals/opens with (the call
// sites that use the shim only ever round-trip a single logical version because
// the DB column travels separately). app.go uses this so workspace/chat/acp/run
// keep the *crypto.Encryptor argument while sharing one KeyedEncryptor.
func NewEncryptorFromKeyed(keyed *KeyedEncryptor, version int) *Encryptor {
	if version < 1 {
		version = 1
	}
	return &Encryptor{keyed: keyed, version: version}
}

// Keyed exposes the underlying KeyedEncryptor so version-aware callers (the
// re-encrypt job, rotate-key endpoint) can use EncryptVersion/DecryptVersion.
func (e *Encryptor) Keyed() *KeyedEncryptor { return e.keyed }

// Encrypt seals plaintext under the shim's version and returns
// nonce || ciphertext || tag (version travels via the DB key_version column).
func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
	return e.keyed.sealWith(context.Background(), e.version, plaintext)
}

// Decrypt verifies and opens a ciphertext produced by Encrypt. It is
// version-agnostic: it tries the active key version then falls back through
// older versions (GCM auth guarantees correctness), so blobs re-sealed onto a
// newer version after a key rotation still open without the call site needing to
// know the row's key_version. Returns an error if input is too short or no key
// authenticates.
func (e *Encryptor) Decrypt(ciphertext []byte) ([]byte, error) {
	return e.keyed.DecryptAny(context.Background(), ciphertext)
}
