package logging

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"gopkg.in/natefinch/lumberjack.v2"
)

// LogConfig contiene la configuración para el sistema de logs
type LogConfig struct {
	BaseDir      string
	BaseFilename string
	MaxSize      int
	MaxBackups   int
	MaxAge       int
	Compress     bool
}

// LoggerSystem maneja los loggers de la aplicación
type LoggerSystem struct {
	Writer      *lumberjack.Logger
	InfoLogger  *log.Logger
	ErrorLogger *log.Logger
}

// Referencias a loggers globales
var (
	InfoLogger  *log.Logger
	ErrorLogger *log.Logger
)

// NewLoggerSystem crea un nuevo sistema de logs
func NewLoggerSystem(config *LogConfig) (*LoggerSystem, error) {
	// Asegurarse de que el directorio base existe
	if err := os.MkdirAll(config.BaseDir, 0755); err != nil {
		return nil, fmt.Errorf("error creando directorio de logs: %w", err)
	}

	logPath := filepath.Join(config.BaseDir, config.BaseFilename)

	logWriter := &lumberjack.Logger{
		Filename:   logPath,
		MaxSize:    config.MaxSize,
		MaxBackups: config.MaxBackups,
		MaxAge:     config.MaxAge,
		Compress:   config.Compress,
		LocalTime:  true,
	}

	system := &LoggerSystem{
		Writer:      logWriter,
		InfoLogger:  log.New(logWriter, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile),
		ErrorLogger: log.New(logWriter, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile),
	}

	return system, nil
}

// Close cierra el sistema de logs
func (ls *LoggerSystem) Close() error {
	return ls.Writer.Close()
}
