package service

import (
	"context"

	"git.itzana.me/strafesnet/maps-service/pkg/api"
)

// SessionRoles implements getSessionRoles operation.
//
// Get bitflags of permissions the currently logged in user has.
//
// GET /session/roles
func (svc *Service) SessionRoles(ctx context.Context) (*api.Roles, error) {
	userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
	if !ok {
		return nil, ErrUserInfo
	}

	roles, err := userInfo.GetRoles();
	if err != nil {
		return nil, err
	}

	return &api.Roles{Roles: int32(roles)}, nil
}

// SessionUser implements sessionUser operation.
//
// Get information about the currently logged in user.
//
// GET /session/roles
func (svc *Service) SessionUser(ctx context.Context) (*api.User, error) {
	userInfoHandle, ok := ctx.Value("UserInfo").(UserInfoHandle)
	if !ok {
		return nil, ErrUserInfo
	}

	userInfo, err := userInfoHandle.GetUserInfo();
	if err != nil {
		return nil, err
	}

	return &api.User{
		UserID:int64(userInfo.UserID),
		Username:userInfo.Username,
		AvatarURL:userInfo.AvatarURL,
	}, nil
}

// SessionUser implements sessionUser operation.
//
// Get information about the currently logged in user.
//
// GET /session/roles
func (svc *Service) SessionValidate(ctx context.Context) (bool, error) {
	userInfoHandle, ok := ctx.Value("UserInfo").(UserInfoHandle)
	if !ok {
		return false, ErrUserInfo
	}

	valid, err := userInfoHandle.Validate();
	if err != nil {
		return false, err
	}

	return valid, nil
}