package main

import (
	"context"
	"errors"
	"gitea.pena/PenaSide/common/validate"
	"gitea.pena/SQuiz/common/dal"
	"gitea.pena/SQuiz/worker/internal/initialize"
	"github.com/caarlos0/env/v8"
	"log"
)

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.KafkaTopicTariff)
	if err != nil {
		log.Fatalf("error validating kafka: %v", err)
	}

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

	err = validate.ValidateSmtp(cfg.ApiKey)
	if err != nil {
		log.Fatalf("error validating smtp: %v", err)
	}

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

	// s3 пока не валидируем пока не слились все ветки
}

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.ServiceName == "" {
		return errors.New("service name is not be empty")
	}

	if cfg.CustomerMicroserviceRPCURL == "" {
		return errors.New("customer microservice rpc url is not be empty")
	}

	if cfg.TelegramToken == "" {
		return errors.New("telegram token is not be empty")
	}

	if cfg.Sender == "" {
		return errors.New("sender is not be empty")
	}

	if cfg.ApiKey == "" {
		return errors.New("api key is not be empty")
	}

	if cfg.ApiUrl == "" {
		return errors.New("api url is not be empty")
	}

	return nil
}
