package auth

import (
	"crypto/subtle"
	"fmt"

	"git.warky.dev/wdevs/amcs/internal/config"
)

type OAuthRegistry struct {
	clients []config.OAuthClient
}

func NewOAuthRegistry(clients []config.OAuthClient) (*OAuthRegistry, error) {
	if len(clients) == 0 {
		return nil, fmt.Errorf("oauth registry requires at least one client")
	}

	return &OAuthRegistry{clients: append([]config.OAuthClient(nil), clients...)}, nil
}

func (o *OAuthRegistry) Lookup(clientID string, clientSecret string) (string, bool) {
	for _, client := range o.clients {
		if subtle.ConstantTimeCompare([]byte(client.ClientID), []byte(clientID)) == 1 &&
			subtle.ConstantTimeCompare([]byte(client.ClientSecret), []byte(clientSecret)) == 1 {
			if client.ID != "" {
				return client.ID, true
			}
			return client.ClientID, true
		}
	}
	return "", false
}
