package services

import (
	"context"

	groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
	"git.coopgo.io/coopgo-platform/groups-management/storage"
	"google.golang.org/grpc"
)

type GroupsManagementService struct {
	groupsmanagement.GroupsManagementClient
}

func NewGroupsManagementService(groupsManagementDial string) (*GroupsManagementService, error) {
	groupsManagementConn, err := grpc.Dial(groupsManagementDial, grpc.WithInsecure())

	client := groupsmanagement.NewGroupsManagementClient(groupsManagementConn)
	if err != nil {
		return nil, err
	}

	return &GroupsManagementService{
		GroupsManagementClient: client,
	}, nil
}

func (s *ServicesHandler) GetGroupsMap() (groups map[string]storage.Group, err error) {
	groups = map[string]storage.Group{}

	request := &groupsmanagement.GetGroupsRequest{
		Namespaces: []string{"parcoursmob_organizations"},
	}
	resp, err := s.GRPC.GroupsManagement.GetGroups(context.TODO(), request)
	if err == nil {
		for _, group := range resp.Groups {
			groups[group.Id] = group.ToStorageType()
		}
	}

	return
}

////////////////////////////////optimize the code//////////////////////////////////////
func (s *ServicesHandler) GetGroupsMemberMap(id string) (groups map[string]any, err error) {
	groups = map[string]any{}

	request := &groupsmanagement.GetGroupsBatchMemberRequest{
		Groupids: []string{id},
	}
	resp, err := s.GRPC.GroupsManagement.GetGroupsBatchMember(context.TODO(), request)
	if err == nil {
		for _, group := range resp.Groups {
			groups[group.Memberid] = group.ToStorageType()
		}
	}
	return
}
