package rpc

import (
	"context"

	"github.com/naiba/nezha/service/dao"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

// AuthHandler ..
type AuthHandler struct {
	ClientID     string
	ClientSecret string
}

// GetRequestMetadata ..
func (a *AuthHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{"client_id": a.ClientID, "client_secret": a.ClientSecret}, nil
}

// RequireTransportSecurity ..
func (a *AuthHandler) RequireTransportSecurity() bool {
	return !dao.Conf.Debug
}

// Check ..
func (a *AuthHandler) Check(ctx context.Context) (clientID string, err error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		err = status.Errorf(codes.Unauthenticated, "获取 metaData 失败")
		return
	}

	var (
		clientSecret string
	)
	if value, ok := md["client_id"]; ok {
		clientID = value[0]
	}
	if value, ok := md["client_secret"]; ok {
		clientSecret = value[0]
	}

	dao.ServerLock.RLock()
	defer dao.ServerLock.RUnlock()
	if server, has := dao.ServerList[clientID]; !has || server.Secret != clientSecret {
		err = status.Errorf(codes.Unauthenticated, "客户端认证失败")
	}
	return
}
