package helper

import (
	"log"
	"os"

	"github.com/getsentry/sentry-go"
)

// LogInfo logs an info message to both the local log and Sentry based on the environment.
func LogInfo(message string) {
	goEnv := os.Getenv("GO_ENV")

	if goEnv == "" {
		log.Fatal("GO_ENV is not set in error_logging LogInfo. Please set the GO_ENV environment variable.")
	}

	if goEnv == "development" || goEnv == "debug" {
		log.Println("INFO:", message)
	}
	if goEnv == "production" || goEnv == "canary" {
		log.Println("INFO:", message)
	}
}

// LogWarn logs a warning message to both the local log and Sentry based on the environment.
func LogWarn(message string) {
	goEnv := os.Getenv("GO_ENV")

	if goEnv == "" {
		log.Fatal("GO_ENV is not set in error_logging LogWarn. Please set the GO_ENV environment variable.")
	}
	if goEnv == "production" || goEnv == "canary" {
		sentry.CaptureMessage("WARNING: " + message)
	} else if goEnv == "development" || goEnv == "debug" {
		log.Println("WARNING:", message)
	}
}

// LogError logs an error message to both the local log and Sentry based on the environment.
func LogError(err error, message string) {
	goEnv := os.Getenv("GO_ENV")

	if goEnv == "" {
		log.Fatal("GO_ENV is not set in error_logging LogError. Please set the GO_ENV environment variable.")
	}

	if goEnv == "production" || goEnv == "canary" {
		if err != nil {
			sentry.CaptureException(err)
		} else {
			sentry.CaptureMessage("ERROR: " + message)
		}
		log.Printf("ERROR: %s: %v", message, err)
	} else if goEnv == "development" || goEnv == "debug" {
		if err != nil {
			log.Printf("ERROR: %s: %v", message, err)
		} else {
			log.Println("ERROR:", message)
		}
	}
}

// LogFatal logs a fatal error message to both the local log and Sentry based on the environment and then exits the application.
func LogFatal(err error, message string) {
	goEnv := os.Getenv("GO_ENV")

	if goEnv == "" {
		log.Fatal("GO_ENV is not set in error_logging LogFatal. Please set the GO_ENV environment variable.")
	}

	if goEnv == "production" || goEnv == "canary" {
		if err != nil {
			sentry.CaptureException(err)
		} else {
			sentry.CaptureMessage("FATAL: " + message)
		}
		log.Fatalf("FATAL: %s: %v", message, err)
	} else if goEnv == "development" || goEnv == "debug" {
		if err != nil {
			log.Fatalf("FATAL: %s: %v", message, err)
		} else {
			log.Fatalf("FATAL: %s", message)
		}
	}
}
