package server

import (
	"net/http"
	"strconv"
)

type AccessContext struct {
	Kind     string
	TenantID int64
	UserID   int64
	Role     string
	Token    string
}

func (s *Server) ResolveAccess(r *http.Request, masterToken uint64) (*AccessContext, bool) {
	tok := BearerToken(r)
	if tok == "" {
		return nil, false
	}

	if tok == strconv.FormatUint(masterToken, 10) {
		return &AccessContext{Kind: "master", Role: "admin", Token: tok}, true
	}

	return s.ResolveTenantAccessToken(tok)
}

func (s *Server) ResolveTenantAccessToken(tok string) (*AccessContext, bool) {
	if tok == "" || s.store == nil {
		return nil, false
	}

	if ss, err := s.store.VerifySessionToken(tok); err == nil && ss != nil {
		return &AccessContext{
			Kind:     "session",
			TenantID: ss.TenantID,
			UserID:   ss.UserID,
			Role:     ss.Role,
			Token:    tok,
		}, true
	}

	if ten, err := s.store.VerifyAPIKey(tok); err == nil && ten != nil {
		return &AccessContext{
			Kind:     "apikey",
			TenantID: ten.ID,
			Role:     "apikey",
			Token:    tok,
		}, true
	}

	return nil, false
}
