/*
  * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 *
*/

package auxhttp

import (
	"encoding/base64"
	"fmt"
	"strings"
)

func EncodeBasicAuth(username, password string) string {
	auth := username + ":" + password
	return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
}

func ParseBasicAuth(basicFields string) (string, string, error) {
	var err error
	var username string
	var password string
	if basicFields == "" {
		err := fmt.Errorf("Empty auth field")
		return username, password, err
	}
	authFields := strings.SplitN(basicFields, " ", 2)
	if len(authFields) < 2 {
		err = fmt.Errorf("Cannot split auth field: %s", basicFields)
		return username, password, err
	}
	authType := strings.TrimSpace(authFields[0])
	if strings.ToLower(authType) != strings.ToLower("Basic") {
		err = fmt.Errorf("Not basic auth type")
		return username, password, err
	}
	authPairEncoded := authFields[1]
	pairEncoded, err := base64.StdEncoding.DecodeString(authPairEncoded)
	if err != nil {
		err = fmt.Errorf("Cannon decode auth pair")
		return username, password, err
	}
	authPair := strings.SplitN(string(pairEncoded), ":", 2)
	if len(authPair) != 2 {
		err = fmt.Errorf("Wrong auth pair")
		return username, password, err
	}
	username = authPair[0]
	password = authPair[1]
	return username, password, err
}
