package ampliimp

import (
	"context"
	"os"

	"github.com/amplitude/analytics-go/amplitude"
	"github.com/tech/sendico/notification/interface/api"
	"github.com/tech/sendico/notification/internal/ampli"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mservice"
	"go.uber.org/zap"
)

type AmplitudeAPI struct {
	logger mlogger.Logger
}

func (a *AmplitudeAPI) Name() mservice.Type {
	return "amplitude"
}

func (a *AmplitudeAPI) Finish(_ context.Context) error {
	ampli.Instance.Flush()
	return nil
}

func CreateAPI(a api.API) (*AmplitudeAPI, error) {
	p := new(AmplitudeAPI)
	p.logger = a.Logger().Named(p.Name())

	env := os.Getenv(a.Config().Amplitude.Environment)
	ampli.Instance.Load(ampli.LoadOptions{
		Environment: ampli.EnvironmentProfeetips,
		Client: ampli.LoadClientOptions{
			Configuration: amplitude.Config{
				Logger:     p.logger.Named("ampli").Sugar(),
				ServerZone: ampli.ServerZoneEU,
			},
		},
	})
	p.logger.Info("Amplitude environment is set", zap.String("ampli_environment", env))

	return p, nil
}
