package server

import (
	"context"
	"errors"

	"git.xeserv.us/xena/route/internal/database"
	"github.com/Xe/ln"
	"golang.org/x/net/trace"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
)

// errors
var (
	ErrNotAuthorized = errors.New("server: not authorized")
)

func (s *Server) getAuth(ctx context.Context, operation, scope string) (database.Token, error) {
	var err error

	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}

	jwtToken, ok := md["authorization"]
	if !ok {
		return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}
	val := jwtToken[0]

	t, err := s.db.GetToken(ctx, val)
	if err != nil {
		return database.Token{}, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}

	ok = false
	for _, sc := range t.Scopes {
		if sc == scope {
			ok = true
		}
	}
	if !ok {
		return database.Token{}, grpc.Errorf(codes.Unauthenticated, "invalid scope.")
	}

	ln.Log(ctx, t)

	return t, nil
}

func handleError(ctx context.Context, clitok database.Token, err error, f ln.F) error {
	tr, ok := trace.FromContext(ctx)
	if !ok {
		goto skip
	}
	tr.SetError()

skip:
	ln.Error(ctx, err, f, clitok)

	return err
}
