// Package crypto wraps AEAD encryption used to protect repo
// passwords, REST-server credentials, hook bodies, and any other
// secret that lands in the SQLite store.
//
// The threat model is "defence in depth against a stolen DB file" —
// not "an attacker with code execution can't read secrets at runtime."
// We need the encryption key at runtime to do any actual work, so
// anyone with a memory dump of the running server can extract it.
package crypto

import (
	stdcipher "crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"os"

	"golang.org/x/crypto/chacha20poly1305"
)

// KeyLen is the required length of the master key (XChaCha20-Poly1305
// uses a 32-byte key). Keys shorter than this are rejected at load.
const KeyLen = chacha20poly1305.KeySize // 32

// AEAD wraps an XChaCha20-Poly1305 instance with a 24-byte random
// nonce per message. Ciphertexts are encoded as
// base64(nonce || ciphertext_with_tag) for SQLite storage.
type AEAD struct {
	cipher stdcipher.AEAD
}

// NewAEAD returns an AEAD using the given 32-byte key.
func NewAEAD(key []byte) (*AEAD, error) {
	if len(key) != KeyLen {
		return nil, fmt.Errorf("crypto: key must be %d bytes, got %d", KeyLen, len(key))
	}
	c, err := chacha20poly1305.NewX(key)
	if err != nil {
		return nil, fmt.Errorf("crypto: init xchacha20poly1305: %w", err)
	}
	return &AEAD{cipher: c}, nil
}

// LoadKeyFromFile reads a 32-byte raw key from path. The file must
// be exactly KeyLen bytes long. Use GenerateKeyFile to mint a fresh
// one on first run.
func LoadKeyFromFile(path string) ([]byte, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("read key file %q: %w", path, err)
	}
	if len(data) != KeyLen {
		return nil, fmt.Errorf("key file %q: expected %d bytes, got %d",
			path, KeyLen, len(data))
	}
	return data, nil
}

// GenerateKeyFile writes a new 32-byte random key to path with mode
// 0600. It refuses to overwrite an existing file.
func GenerateKeyFile(path string) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
	if err != nil {
		return fmt.Errorf("create key file %q: %w", path, err)
	}
	defer func() { _ = f.Close() }()
	key := make([]byte, KeyLen)
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		return fmt.Errorf("read random: %w", err)
	}
	if _, err := f.Write(key); err != nil {
		return fmt.Errorf("write key: %w", err)
	}
	return nil
}

// Encrypt seals plaintext under a fresh random nonce. The returned
// string is base64(nonce || ciphertext_with_tag) and is what gets
// stored in TEXT columns. Optional additionalData binds the
// ciphertext to a context (e.g. the row's primary key) so a swap
// attack between rows is detectable.
func (a *AEAD) Encrypt(plaintext, additionalData []byte) (string, error) {
	nonce := make([]byte, a.cipher.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return "", fmt.Errorf("crypto: read nonce: %w", err)
	}
	ct := a.cipher.Seal(nil, nonce, plaintext, additionalData)
	out := make([]byte, 0, len(nonce)+len(ct))
	out = append(out, nonce...)
	out = append(out, ct...)
	return base64.StdEncoding.EncodeToString(out), nil
}

// Decrypt reverses Encrypt.
func (a *AEAD) Decrypt(ciphertext string, additionalData []byte) ([]byte, error) {
	raw, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return nil, fmt.Errorf("crypto: base64 decode: %w", err)
	}
	if len(raw) < a.cipher.NonceSize()+a.cipher.Overhead() {
		return nil, errors.New("crypto: ciphertext too short")
	}
	nonce := raw[:a.cipher.NonceSize()]
	ct := raw[a.cipher.NonceSize():]
	pt, err := a.cipher.Open(nil, nonce, ct, additionalData)
	if err != nil {
		return nil, fmt.Errorf("crypto: open: %w", err)
	}
	return pt, nil
}
