package auth

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

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

// argon2id parameters. Tuned for a control-plane login path: ~64 MiB memory,
// single pass, 4 lanes. Kept as constants so the encoded hash is self-describing
// and parameters can evolve without breaking existing hashes (params are parsed
// back out of the stored string at verify time).
const (
	argonMemory  uint32 = 64 * 1024 // KiB → 64 MiB
	argonTime    uint32 = 1
	argonThreads uint8  = 4
	argonKeyLen  uint32 = 32
	argonSaltLen        = 16
)

// errInvalidHash is returned when a stored PHC string cannot be parsed.
var errInvalidHash = errors.New("auth: invalid argon2id hash format")

// HashPassword derives an argon2id hash and returns it in the standard PHC
// string format: $argon2id$v=19$m=...,t=...,p=...$<salt>$<hash>.
func HashPassword(password string) (string, error) {
	salt := make([]byte, argonSaltLen)
	if _, err := rand.Read(salt); err != nil {
		return "", fmt.Errorf("auth: read salt: %w", err)
	}
	return encodeArgon(password, salt, argonTime, argonMemory, argonThreads, argonKeyLen), nil
}

// encodeArgon computes the hash and formats the PHC string.
func encodeArgon(password string, salt []byte, t, m uint32, p uint8, keyLen uint32) string {
	key := argon2.IDKey([]byte(password), salt, t, m, p, keyLen)
	return fmt.Sprintf(
		"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, m, t, p,
		base64.RawStdEncoding.EncodeToString(salt),
		base64.RawStdEncoding.EncodeToString(key),
	)
}

// VerifyPassword reports whether password matches the encoded argon2id hash.
// The comparison is constant-time. A malformed encoded hash returns false with
// an error so callers can distinguish "wrong password" from "corrupt record".
func VerifyPassword(encoded, password string) (bool, error) {
	t, m, p, salt, key, err := decodeArgon(encoded)
	if err != nil {
		return false, err
	}
	other := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(key)))
	if subtle.ConstantTimeCompare(key, other) == 1 {
		return true, nil
	}
	return false, nil
}

// decodeArgon parses a PHC argon2id string back into its parameters.
func decodeArgon(encoded string) (t, m uint32, p uint8, salt, key []byte, err error) {
	parts := strings.Split(encoded, "$")
	// ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, key]
	if len(parts) != 6 || parts[1] != "argon2id" {
		return 0, 0, 0, nil, nil, errInvalidHash
	}

	var version int
	if _, err = fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
		return 0, 0, 0, nil, nil, errInvalidHash
	}
	if version != argon2.Version {
		return 0, 0, 0, nil, nil, errInvalidHash
	}
	if _, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil {
		return 0, 0, 0, nil, nil, errInvalidHash
	}
	if salt, err = base64.RawStdEncoding.DecodeString(parts[4]); err != nil {
		return 0, 0, 0, nil, nil, errInvalidHash
	}
	if key, err = base64.RawStdEncoding.DecodeString(parts[5]); err != nil {
		return 0, 0, 0, nil, nil, errInvalidHash
	}
	return t, m, p, salt, key, nil
}

// dummyHash is a pre-computed argon2id hash used to spend roughly the same CPU
// time when a login targets a non-existent account, keeping the login response
// time constant regardless of whether the email exists. Computed lazily once.
var dummyHash = mustDummyHash()

func mustDummyHash() string {
	h, err := HashPassword("pangolin-constant-time-placeholder")
	if err != nil {
		// Fall back to a static PHC string; verification will simply fail.
		return "$argon2id$v=19$m=65536,t=1,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
	}
	return h
}

// ConstantTimeReject performs a throwaway argon2id verification against a dummy
// hash. Login handlers call this when the account does not exist so the timing
// profile matches the "account exists, wrong password" branch.
func ConstantTimeReject(password string) {
	_, _ = VerifyPassword(dummyHash, password)
}
