// File Path: monorepo/cloud/maplepress-backend/pkg/security/password/password.go
package password

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

	"golang.org/x/crypto/argon2"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/security/securestring"
)

var (
	ErrInvalidHash         = errors.New("the encoded hash is not in the correct format")
	ErrIncompatibleVersion = errors.New("incompatible version of argon2")
	ErrPasswordTooShort    = errors.New("password must be at least 8 characters")
	ErrPasswordTooLong     = errors.New("password must not exceed 128 characters")

	// Granular password strength errors (CWE-521: Weak Password Requirements)
	ErrPasswordNoUppercase   = errors.New("password must contain at least one uppercase letter (A-Z)")
	ErrPasswordNoLowercase   = errors.New("password must contain at least one lowercase letter (a-z)")
	ErrPasswordNoNumber      = errors.New("password must contain at least one number (0-9)")
	ErrPasswordNoSpecialChar = errors.New("password must contain at least one special character (!@#$%^&*()_+-=[]{}; etc.)")
	ErrPasswordTooWeak       = errors.New("password must contain uppercase, lowercase, number, and special character")
)

// PasswordProvider provides secure password hashing and verification using Argon2id.
type PasswordProvider interface {
	GenerateHashFromPassword(password *securestring.SecureString) (string, error)
	ComparePasswordAndHash(password *securestring.SecureString, hash string) (bool, error)
	AlgorithmName() string
	GenerateSecureRandomBytes(length int) ([]byte, error)
	GenerateSecureRandomString(length int) (string, error)
}

type passwordProvider struct {
	memory      uint32
	iterations  uint32
	parallelism uint8
	saltLength  uint32
	keyLength   uint32
}

// NewPasswordProvider creates a new password provider with secure default parameters.
// The default parameters are based on OWASP recommendations for Argon2id:
// - Memory: 64 MB
// - Iterations: 3
// - Parallelism: 2
// - Salt length: 16 bytes
// - Key length: 32 bytes
func NewPasswordProvider() PasswordProvider {
	// DEVELOPERS NOTE:
	// The following code was adapted from: "How to Hash and Verify Passwords With Argon2 in Go"
	// via https://www.alexedwards.net/blog/how-to-hash-and-verify-passwords-with-argon2-in-go

	// Establish the parameters to use for Argon2
	return &passwordProvider{
		memory:      64 * 1024, // 64 MB
		iterations:  3,
		parallelism: 2,
		saltLength:  16,
		keyLength:   32,
	}
}

// GenerateHashFromPassword takes a secure string and returns an Argon2id hashed string.
// The returned hash string includes all parameters needed for verification:
// Format: $argon2id$v=19$m=65536,t=3,p=2$<base64-salt>$<base64-hash>
func (p *passwordProvider) GenerateHashFromPassword(password *securestring.SecureString) (string, error) {
	salt, err := generateRandomBytes(p.saltLength)
	if err != nil {
		return "", fmt.Errorf("failed to generate salt: %w", err)
	}

	passwordBytes := password.Bytes()

	// Generate the hash using Argon2id
	hash := argon2.IDKey(passwordBytes, salt, p.iterations, p.memory, p.parallelism, p.keyLength)

	// Base64 encode the salt and hashed password
	b64Salt := base64.RawStdEncoding.EncodeToString(salt)
	b64Hash := base64.RawStdEncoding.EncodeToString(hash)

	// Return a string using the standard encoded hash representation
	encodedHash := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash)

	return encodedHash, nil
}

// ComparePasswordAndHash verifies that a password matches the provided hash.
// It uses constant-time comparison to prevent timing attacks.
// Returns true if the password matches, false otherwise.
func (p *passwordProvider) ComparePasswordAndHash(password *securestring.SecureString, encodedHash string) (match bool, err error) {
	// DEVELOPERS NOTE:
	// The following code was adapted from: "How to Hash and Verify Passwords With Argon2 in Go"
	// via https://www.alexedwards.net/blog/how-to-hash-and-verify-passwords-with-argon2-in-go

	// Extract the parameters, salt and derived key from the encoded password hash
	params, salt, hash, err := decodeHash(encodedHash)
	if err != nil {
		return false, err
	}

	// Derive the key from the password using the same parameters
	otherHash := argon2.IDKey(password.Bytes(), salt, params.iterations, params.memory, params.parallelism, params.keyLength)

	// Check that the contents of the hashed passwords are identical
	// Using subtle.ConstantTimeCompare() to help prevent timing attacks
	if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
		return true, nil
	}
	return false, nil
}

// AlgorithmName returns the name of the hashing algorithm used.
func (p *passwordProvider) AlgorithmName() string {
	return "argon2id"
}

// GenerateSecureRandomBytes generates a cryptographically secure random byte slice.
func (p *passwordProvider) GenerateSecureRandomBytes(length int) ([]byte, error) {
	bytes := make([]byte, length)
	_, err := rand.Read(bytes)
	if err != nil {
		return nil, fmt.Errorf("failed to generate secure random bytes: %w", err)
	}
	return bytes, nil
}

// GenerateSecureRandomString generates a cryptographically secure random hex string.
// The returned string will be twice the length parameter (2 hex chars per byte).
func (p *passwordProvider) GenerateSecureRandomString(length int) (string, error) {
	bytes, err := p.GenerateSecureRandomBytes(length)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

// generateRandomBytes generates cryptographically secure random bytes.
func generateRandomBytes(n uint32) ([]byte, error) {
	// DEVELOPERS NOTE:
	// The following code was adapted from: "How to Hash and Verify Passwords With Argon2 in Go"
	// via https://www.alexedwards.net/blog/how-to-hash-and-verify-passwords-with-argon2-in-go

	b := make([]byte, n)
	_, err := rand.Read(b)
	if err != nil {
		return nil, err
	}

	return b, nil
}

// decodeHash extracts the parameters, salt, and hash from an encoded hash string.
func decodeHash(encodedHash string) (p *passwordProvider, salt, hash []byte, err error) {
	// DEVELOPERS NOTE:
	// The following code was adapted from: "How to Hash and Verify Passwords With Argon2 in Go"
	// via https://www.alexedwards.net/blog/how-to-hash-and-verify-passwords-with-argon2-in-go

	vals := strings.Split(encodedHash, "$")
	if len(vals) != 6 {
		return nil, nil, nil, ErrInvalidHash
	}

	var version int
	_, err = fmt.Sscanf(vals[2], "v=%d", &version)
	if err != nil {
		return nil, nil, nil, err
	}
	if version != argon2.Version {
		return nil, nil, nil, ErrIncompatibleVersion
	}

	p = &passwordProvider{}
	_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism)
	if err != nil {
		return nil, nil, nil, err
	}

	salt, err = base64.RawStdEncoding.Strict().DecodeString(vals[4])
	if err != nil {
		return nil, nil, nil, err
	}
	p.saltLength = uint32(len(salt))

	hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[5])
	if err != nil {
		return nil, nil, nil, err
	}
	p.keyLength = uint32(len(hash))

	return p, salt, hash, nil
}
