package log

import (
	"fmt"
	"io"
	"os"
	"path"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
)

// Initialize initializes a logger instance with given
// level, filepath, filename, maxSize, maxAge and rotationTime.
func Initialize(opts ...Option) (io.Writer, error) {
	config := generateConfig(opts...)

	if err := os.MkdirAll(config.filePath, os.ModePerm); err != nil {
		return nil, fmt.Errorf("create file path: %w", err)
	}

	o := &out{
		fileOut: nil,
		stdout:  os.Stdout,
	}
	if config.persist {
		baseLogName := path.Join(config.filePath, config.fileName)
		writer, err := rotatelogs.New(
			baseLogName+"%Y%m%d%H%M%S",
			rotatelogs.WithLinkName(baseLogName),
			rotatelogs.WithMaxAge(config.maxAge),
			rotatelogs.WithRotationTime(config.rotationTime),
		)
		if err != nil {
			return nil, err
		}
		o.fileOut = writer
	}

	return o, nil
}

type out struct {
	fileOut io.Writer
	stdout  io.Writer
}

func (o *out) Write(p []byte) (n int, err error) {
	_, _ = o.stdout.Write(p)
	return o.fileOut.Write(p)
}
