package boxstore

import (
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"strings"
	"time"

	"golang.org/x/crypto/bcrypt"

	"warpbox/lib/models"
)

func IsExpired(manifest models.BoxManifest) bool {
	return !manifest.ExpiresAt.IsZero() && time.Now().UTC().After(manifest.ExpiresAt)
}

func IsPasswordProtected(manifest models.BoxManifest) bool {
	return manifest.PasswordHash != "" && manifest.AuthToken != ""
}

func VerifyPassword(manifest models.BoxManifest, password string) bool {
	if !IsPasswordProtected(manifest) {
		return true
	}

	expected := manifest.PasswordHash
	if manifest.PasswordHashAlg == "bcrypt" || strings.HasPrefix(expected, "$2") {
		return bcrypt.CompareHashAndPassword([]byte(expected), []byte(password)) == nil
	}

	actual := legacyPasswordHash(manifest.PasswordSalt, password)
	return subtle.ConstantTimeCompare([]byte(expected), []byte(actual)) == 1
}

func VerifyAuthToken(manifest models.BoxManifest, token string) bool {
	if !IsPasswordProtected(manifest) {
		return true
	}

	if token == "" {
		return false
	}

	return subtle.ConstantTimeCompare([]byte(manifest.AuthToken), []byte(token)) == 1
}
func legacyPasswordHash(salt string, password string) string {
	sum := sha256.Sum256([]byte(salt + ":" + password))
	return hex.EncodeToString(sum[:])
}
