package main

import (
	"context"
	SolidarityServiceHandler "solidarity-service/handler"
	api "solidarity-service/interoperability/solidarity-api/server"
	grpcserver "solidarity-service/servers/grpc/server"
	"solidarity-service/storage"
	"strconv"

	routing "git.coopgo.io/coopgo-platform/routing-service"
	formancesdkgo "github.com/formancehq/formance-sdk-go/v3"
	"github.com/formancehq/formance-sdk-go/v3/pkg/models/operations"
	"github.com/formancehq/formance-sdk-go/v3/pkg/models/shared"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

func main() {
	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

	cfg, err := ReadConfig()
	if err != nil {
		panic(err)
	}

	var (
		serviceName         = cfg.GetString("name")
		grpcEnable          = cfg.GetBool("services.grpc.enable")
		solidarityApiEnable = cfg.GetBool("services.solidarity-api.enable")
		routingServiceType  = cfg.GetString("routing.type")
		valhallaBaseUrl     = cfg.GetString("routing.valhalla.base_url")
	)
	log.Info().Msg("Running " + serviceName)
	storageService, err := storage.NewStorage(cfg)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the storage service")
		return
	}
	routing, err := routing.NewRoutingService(routingServiceType, valhallaBaseUrl)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the routing service")
		return
	}
	handler, err := SolidarityServiceHandler.NewSolidarityServiceHandler(cfg, routing, storageService)
	if err != nil {
		log.Fatal().Err(err).Msg("Could not initiate the solidarity service handler")
		return
	}

	failed := make(chan error)
	if grpcEnable {
		log.Info().Msg("Running gRPC server")
		go grpcserver.Run(failed, cfg, handler)
	}

	if solidarityApiEnable {
		log.Info().Msg("Running Interoperability REST API")
		go api.Run(cfg, handler, storageService)
	}

	err = <-failed

	log.Fatal().Err(err).Msg("Terminating")

	 s := formancesdkgo.New(
    	formancesdkgo.WithServerURL("https://10.73.189.26"),
        formancesdkgo.WithSecurity(shared.Security{
            ClientID: formancesdkgo.String("<YOUR_CLIENT_ID_HERE>"),
            ClientSecret: formancesdkgo.String("<YOUR_CLIENT_SECRET_HERE>"),
        }),
    )

    ctx := context.Background()
    res, err := s.Ledger.V2.ListLedgers(ctx, operations.V2ListLedgersRequest{
        PageSize: formancesdkgo.Int64(100),
    })
    if err != nil {
        log.Fatal().Err(err).Msg("Formance Ledger initialitation error")
    }
    log.Info().Msg("response:"+ strconv.Itoa(res.StatusCode))
}
