package main

import (
	"context"
	"errors"
	"gitea.pena/PenaSide/common/validate"
	"gitea.pena/SQuiz/common/dal"
	"gitea.pena/SQuiz/core/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 = dal.New(context.TODO(), cfg.PostgresURL, nil)
	if err != nil {
		log.Fatalf("error connecting to database postgres: %v", err)
	}

	_, err = dal.NewClickHouseDAL(context.TODO(), cfg.ClickhouseURL)
	if err != nil {
		log.Fatalf("error connecting to database clickhouse: %v", err)
	}

	err = validate.ValidateKafka([]string{cfg.KafkaBrokers}, cfg.KafkaTopicNotifyer)
	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)
	}
	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 dont be empty")
	}

	if cfg.GrpcURL == "" {
		return errors.New("grpc url dont be empty")
	}

	if cfg.HubadminMicroserviceURL == "" {
		return errors.New("hubadmin microservice url dont be empty")
	}

	if cfg.AuthMicroserviceURL == "" {
		return errors.New("auth microservice url dont be empty")
	}

	if cfg.TrashLogHost == "" {
		return errors.New("trash log host dont be empty")
	}

	if cfg.S3Prefix == "" {
		return errors.New("s3 prefix dont be empty")
	}

	if cfg.ServiceName == "" {
		return errors.New("service name dont be empty")
	}

	return nil
}
