package crypto

import (
	"fmt"
	"strconv"
	"strings"
)

type PasswordHash struct {
	Algorithm  string
	Iterations int
	Salt       string
	Hash       string
}

func (h *PasswordHash) String() string {
	return fmt.Sprintf("%s$%d$%s$%s", h.Algorithm, h.Iterations, h.Salt, h.Hash)
}

func ParsePasswordHash(encryptedPassword string) (*PasswordHash, error) {
	// split the encrypted password into 4 parts
	// pbkdf2-sha512$20000$<salt>$<hash>
	// 0              1      2       3
	parts := strings.Split(encryptedPassword, "$")
	if len(parts) != 4 {
		return nil, fmt.Errorf("invalid pbkdf2 hash")
	}
	iterations, err := strconv.Atoi(parts[1])
	if err != nil {
		return nil, err
	}
	return &PasswordHash{
		Algorithm:  parts[0],
		Iterations: iterations,
		Salt:       parts[2],
		Hash:       parts[3],
	}, nil
}
