package main

import (
	"context"
	"fmt"
	"gitea.pena/PenaSide/common/validate"
	"gitea.pena/PenaSide/heruvym/internal/initialize"
	minioDal "gitea.pena/PenaSide/heruvym/internal/repository/minio"
	"github.com/caarlos0/env/v8"
	"log"
)

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

	if cfg.ClientHttpUrl == "" {
		log.Fatalf("error client http url is empty")
	}

	if cfg.AdminHttpUrl == "" {
		log.Fatalf("error admin http url is empty")
	}

	err = validate.ValidateMongo(cfg.ExternalCfg.Database)
	if err != nil {
		log.Fatalf("error validating mongo: %v", err)
	}

	err = validate.ValidateTgToken(cfg.TelegramToken)
	if err != nil {
		log.Fatalf("error validating telegram token: %v", err)
	}

	if cfg.TelegramChannelID == 0 {
		log.Fatalf("telegram channel id must be set")
	}

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

	err = validate.ValidateS3(validate.ValidateS3Deps{
		S3Endpoint:  cfg.S3Endpoint,
		S3Token:     cfg.S3Token,
		S3AccessKey: cfg.S3AccessKey,
		S3SecretKey: cfg.S3SecretKey,
		BucketName:  minioDal.Bucket,
		IsProd:      cfg.IsProd,
	})
	if err != nil {
		log.Fatalf("error validating s3: %v", err)
	}
}

func loadConfig() (initialize.Config, error) {
	var config initialize.Config
	if err := env.Parse(&config); err != nil {
		return config, err
	}

	return config, nil
}

func validateRedis(cfg initialize.Config) error {
	if cfg.RedisHost == "" {
		return fmt.Errorf("redis host is empty")
	}

	_, err := initialize.Redis(context.TODO(), cfg)
	if err != nil {
		return err
	}
	return nil
}
