package serverimp

import (
	"context"
	"os"
	"strings"
	"time"

	"github.com/tech/sendico/ledger/internal/service/ledger"
	"github.com/tech/sendico/ledger/storage"
	mongostorage "github.com/tech/sendico/ledger/storage/mongo"
	"github.com/tech/sendico/pkg/api/routers"
	"github.com/tech/sendico/pkg/db"
	msg "github.com/tech/sendico/pkg/messaging"
	"github.com/tech/sendico/pkg/mlogger"
	feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
	"github.com/tech/sendico/pkg/server/grpcapp"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gopkg.in/yaml.v3"
)

type Imp struct {
	logger mlogger.Logger
	file   string
	debug  bool

	config   *config
	app      *grpcapp.App[storage.Repository]
	service  *ledger.Service
	feesConn *grpc.ClientConn
}

type config struct {
	*grpcapp.Config `yaml:",inline"`
	Fees            FeesClientConfig `yaml:"fees"`
}

type FeesClientConfig struct {
	Address        string `yaml:"address"`
	TimeoutSeconds int    `yaml:"timeout_seconds"`
}

const defaultFeesTimeout = 3 * time.Second

func (c FeesClientConfig) timeout() time.Duration {
	if c.TimeoutSeconds <= 0 {
		return defaultFeesTimeout
	}
	return time.Duration(c.TimeoutSeconds) * time.Second
}

func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
	return &Imp{
		logger: logger.Named("server"),
		file:   file,
		debug:  debug,
	}, nil
}

func (i *Imp) Shutdown() {
	if i.app == nil {
		if i.service != nil {
			i.service.Shutdown()
		}
		if i.feesConn != nil {
			_ = i.feesConn.Close()
		}
		return
	}

	timeout := 15 * time.Second
	if i.config != nil && i.config.Runtime != nil {
		timeout = i.config.Runtime.ShutdownTimeout()
	}

	if i.service != nil {
		i.service.Shutdown()
	}

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	i.app.Shutdown(ctx)
	cancel()

	if i.feesConn != nil {
		_ = i.feesConn.Close()
	}
}

func (i *Imp) Start() error {
	cfg, err := i.loadConfig()
	if err != nil {
		return err
	}
	i.config = cfg

	repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
		return mongostorage.New(logger, conn)
	}

	var feesClient feesv1.FeeEngineClient
	feesTimeout := cfg.Fees.timeout()
	if addr := strings.TrimSpace(cfg.Fees.Address); addr != "" {
		ctx, cancel := context.WithTimeout(context.Background(), feesTimeout)
		defer cancel()

		conn, err := grpc.DialContext(ctx, addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
		if err != nil {
			i.logger.Warn("Failed to connect to fees service", zap.String("address", addr), zap.Error(err))
		} else {
			i.logger.Info("Connected to fees service", zap.String("address", addr))
			i.feesConn = conn
			feesClient = feesv1.NewFeeEngineClient(conn)
		}
	}

	serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
		invokeURI := ""
		if cfg.GRPC != nil {
			invokeURI = cfg.GRPC.DiscoveryInvokeURI()
		}
		svc := ledger.NewService(logger, repo, producer, feesClient, feesTimeout, invokeURI)
		i.service = svc
		return svc, nil
	}

	app, err := grpcapp.NewApp(i.logger, "ledger", cfg.Config, i.debug, repoFactory, serviceFactory)
	if err != nil {
		return err
	}
	i.app = app

	return i.app.Start()
}

func (i *Imp) loadConfig() (*config, error) {
	data, err := os.ReadFile(i.file)
	if err != nil {
		i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
		return nil, err
	}

	cfg := &config{Config: &grpcapp.Config{}}
	if err := yaml.Unmarshal(data, cfg); err != nil {
		i.logger.Error("Failed to parse configuration", zap.Error(err))
		return nil, err
	}

	if cfg.Runtime == nil {
		cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
	}

	if cfg.GRPC == nil {
		cfg.GRPC = &routers.GRPCConfig{
			Network:          "tcp",
			Address:          ":50052",
			EnableReflection: true,
			EnableHealth:     true,
		}
	}

	return cfg, nil
}
