package logger

import (
	"io"
	"os"

	"github.com/sirupsen/logrus"
)

var DefaultLogger *logrus.Logger

func init() {
	DefaultLogger = logrus.New()
	DefaultLogger.SetLevel(logrus.InfoLevel)
	DefaultLogger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})
}

// SetupLogger configures the logger with the specified level
func SetupLogger(level string) *logrus.Logger {
	logger := logrus.New()

	switch level {
	case "debug":
		logger.SetLevel(logrus.DebugLevel)
	case "info":
		logger.SetLevel(logrus.InfoLevel)
	case "warn":
		logger.SetLevel(logrus.WarnLevel)
	case "error":
		logger.SetLevel(logrus.ErrorLevel)
	default:
		logger.SetLevel(logrus.InfoLevel)
	}

	logger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})

	return logger
}

// SetupJSONLogger creates a logger with JSON formatting
func SetupJSONLogger(level string) *logrus.Logger {
	logger := SetupLogger(level)
	logger.SetFormatter(&logrus.JSONFormatter{})
	return logger
}

// SetupFileLogger creates a logger that writes to a file
func SetupFileLogger(level, filepath string) (*logrus.Logger, error) {
	logger := SetupLogger(level)

	file, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		return nil, err
	}

	// Write to both file and stdout
	logger.SetOutput(io.MultiWriter(os.Stdout, file))
	return logger, nil
}
