package services

import (
	agenda "git.coopgo.io/coopgo-platform/agenda/grpcapi"
	fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
	groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
	mobilityaccounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
	routing "git.coopgo.io/coopgo-platform/routing-service"
	solidarityservice "git.coopgo.io/sbouaram/solidarity-service/servers/grpc/proto"

	"github.com/spf13/viper"
	"github.com/rs/zerolog/log"
)

type ServicesHandler struct {
	GRPC GRPCServices
}

type GRPCServices struct {
	MobilityAccounts  mobilityaccounts.MobilityAccountsClient
	GroupsManagement  groupsmanagement.GroupsManagementClient
	Fleets            fleets.FleetsClient
	Agenda            agenda.AgendaClient
	SolidarityService solidarityservice.SolidarityServiceClient

	Routing          routing.RoutingService
}

func NewServicesHandler(cfg *viper.Viper) (*ServicesHandler, error) {
	var (
		mobilityAccountsDial = cfg.GetString("services.grpc.mobilityaccounts.dial")
		groupsManagementDial = cfg.GetString("services.grpc.groupsmanagement.dial")
		fleetsDial           = cfg.GetString("services.grpc.fleets.dial")
		agendaDial           = cfg.GetString("services.grpc.agenda.dial")
		solidarityDial   = cfg.GetString("services.grpc.solidarityservice.dial")
		routing_service_type = cfg.GetString("routing.type")
		valhalla_base_url    = cfg.GetString("routing.valhalla.base_url")
	)
	mobilityAccounts, err := NewMobilityAccountService(mobilityAccountsDial)
	if err != nil {
		return nil, err
	}

	groupsManagement, err := NewGroupsManagementService(groupsManagementDial)
	if err != nil {
		return nil, err
	}

	fleetsSvc, err := NewFleetsService(fleetsDial)
	if err != nil {
		return nil, err
	}

	agendaSvc, err := NewAgendaService(agendaDial)
	if err != nil {
		return nil, err
	}

	solidarityService, err := NewSolidarityService(solidarityDial)
	if err != nil {
		return nil , err
	}

	

	routing, err := routing.NewRoutingService(routing_service_type, valhalla_base_url)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the routing service")
		return nil, err
	}

	return &ServicesHandler{
		GRPC: GRPCServices{
			MobilityAccounts: mobilityAccounts,
			GroupsManagement: groupsManagement,
			Fleets:           fleetsSvc,
			Agenda:           agendaSvc,
			SolidarityService: solidarityService,
			Routing: routing,
		},
	}, nil
}
