// Package loglevel implements a basic level based logger
package loglevel

import (
	"fmt"
	"io"
	"log/slog"
	"os"
	"path"
)

// Logger defines a logger that rotates the logs in a file
type Logger struct {
	fr *FileRotater
}

// Init creates a new logger
// The dir is the path where the log file is stored
func (l *Logger) Init(dir string) (*slog.Logger, error) {
	err := os.MkdirAll(dir, 0o700)
	if err != nil {
		return nil, err
	}
	name := path.Join(dir, "log")

	fr, err := NewFileRotater(name)
	if err != nil {
		return nil, fmt.Errorf("failed creating log rotater: %w", err)
	}
	l.fr = fr
	multi := io.MultiWriter(os.Stdout, fr)
	handler := slog.NewTextHandler(multi, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	})
	return slog.New(handler), nil
}

// Close cleans up the logger, meaning closes the logger file
func (l *Logger) Close() error {
	return l.fr.Close()
}
