package main

import (
	"amocrm/internal/initialize"
	"context"
	"errors"
	"gitea.pena/PenaSide/common/validate"
	"github.com/caarlos0/env/v8"
	"log"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal"
)

func main() {
	cfg, err := loadConfig()
	if err != nil {
		log.Fatalf("error loading config: %v", err)
	}

	err = validateNotEmpty(cfg)
	if err != nil {
		log.Fatalf("error validating config: %v", err)
	}

	err = validate.ValidateKafka([]string{cfg.KafkaBrokers}, cfg.KafkaTopicQueueAmo)
	if err != nil {
		log.Fatalf("error validating Kafka: %v", err)
	}

	err = validate.ValidateRedis(cfg.RedisHost, cfg.RedisPassword, cfg.RedisDB)
	if err != nil {
		log.Fatalf("error validating Redis: %v", err)
	}

	_, err = dal.NewAmoDal(context.TODO(), cfg.PostgresURL)
	if err != nil {
		log.Fatalf("error connecting to postgres: %v", err)
	}

	return
}

func loadConfig() (initialize.Config, error) {
	var cfg initialize.Config

	if err := env.Parse(&cfg); err != nil {
		return cfg, err
	}
	return cfg, nil
}

func validateNotEmpty(cfg initialize.Config) error {
	if cfg.ClientHttpURL == "" {
		return errors.New("client http url cannot be empty")
	}

	if cfg.OauthReturnURL == "" {
		return errors.New("oauth returning url cannot be empty")
	}

	if cfg.PenaSocialAuthMicroserviceURL == "" {
		return errors.New("pena social auth microservice url cannot be empty")
	}

	if cfg.AmoIntegrationID == "" {
		return errors.New("amo integration id cannot be empty")
	}

	if cfg.AmoIntegrationSecret == "" {
		return errors.New("amo integration secret cannot be empty")
	}

	if cfg.QuizIntegrationsRedirectURL == "" {
		return errors.New("quiz integrations redirect url cannot be empty")
	}

	return nil
}
