// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT

package turn

import (
	
	 //nolint:gosec,gci
	
	
	
	
	

	
)

// GenerateLongTermCredentials can be used to create credentials valid for [duration] time.
func ( string,  time.Duration) (string, string, error) {
	 := time.Now().Add().Unix()
	 := strconv.FormatInt(, 10)
	,  := longTermCredentials(, )

	return , , 
}

// GenerateLongTermTURNRESTCredentials can be used to create credentials valid for [duration] time.
func ( string,  string,  time.Duration) (
	string,
	string,
	error,
) {
	 := time.Now().Add().Unix()
	 := strconv.FormatInt(, 10)
	 :=  + ":" + 
	,  := longTermCredentials(, )

	return , , 
}

func longTermCredentials( string,  string) (string, error) {
	 := hmac.New(sha1.New, []byte())
	,  := .Write([]byte())
	if  != nil {
		return "",  // Not sure if this will ever happen
	}
	 := .Sum(nil)

	return base64.StdEncoding.EncodeToString(), nil
}

// NewLongTermAuthHandler returns a turn.AuthAuthHandler used with Long Term (or Time Windowed) Credentials.
// See: https://datatracker.ietf.org/doc/html/rfc8489#section-9.2
// .
func ( string,  logging.LeveledLogger) AuthHandler {
	if  == nil {
		 = logging.NewDefaultLoggerFactory().NewLogger("turn")
	}

	return func(,  string,  net.Addr) ( []byte,  bool) {
		.Tracef("Authentication username=%q realm=%q srcAddr=%v", , , )
		,  := strconv.Atoi()
		if  != nil {
			.Errorf("Invalid time-windowed username %q", )

			return nil, false
		}
		if int64() < time.Now().Unix() {
			.Errorf("Expired time-windowed username %q", )

			return nil, false
		}
		,  := longTermCredentials(, )
		if  != nil {
			.Error(.Error())

			return nil, false
		}

		return GenerateAuthKey(, , ), true
	}
}

// LongTermTURNRESTAuthHandler returns a turn.AuthAuthHandler that can be used to authenticate
// time-windowed ephemeral credentials generated by the TURN REST API as described in
// https://datatracker.ietf.org/doc/html/draft-uberti-behave-turn-rest-00
//
// The supported format of is timestamp:username, where username is an arbitrary user id and the
// timestamp specifies the expiry of the credential.
func ( string,  logging.LeveledLogger) AuthHandler {
	if  == nil {
		 = logging.NewDefaultLoggerFactory().NewLogger("turn")
	}

	return func(,  string,  net.Addr) ( []byte,  bool) {
		.Tracef("Authentication username=%q realm=%q srcAddr=%v", , , )
		 := strings.Split(, ":")[0]
		,  := strconv.Atoi()
		if  != nil {
			.Errorf("Invalid time-windowed username %q", )

			return nil, false
		}
		if int64() < time.Now().Unix() {
			.Errorf("Expired time-windowed username %q", )

			return nil, false
		}
		,  := longTermCredentials(, )
		if  != nil {
			.Error(.Error())

			return nil, false
		}

		return GenerateAuthKey(, , ), true
	}
}