package logging

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type dailyWriter struct {
	mu       sync.Mutex
	dir      string
	prefix   string
	location *time.Location
	day      string
	file     *os.File
}

func newDailyWriter(dir string, prefix string, location *time.Location) *dailyWriter {
	return &dailyWriter{
		dir:      dir,
		prefix:   prefix,
		location: location,
	}
}

func (w *dailyWriter) Write(p []byte) (int, error) {
	w.mu.Lock()
	defer w.mu.Unlock()

	if err := w.rotateIfNeeded(time.Now().In(w.location)); err != nil {
		return 0, err
	}
	return w.file.Write(p)
}

func (w *dailyWriter) Sync() error {
	w.mu.Lock()
	defer w.mu.Unlock()

	if w.file == nil {
		return nil
	}
	return w.file.Sync()
}

func (w *dailyWriter) rotateIfNeeded(now time.Time) error {
	day := now.Format("2006-01-02")
	if w.file != nil && w.day == day {
		return nil
	}

	if err := os.MkdirAll(w.dir, 0o755); err != nil {
		return err
	}

	if w.file != nil {
		_ = w.file.Close()
		w.file = nil
	}

	path := filepath.Join(w.dir, fmt.Sprintf("%s-%s.log", w.prefix, day))
	file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
	if err != nil {
		return err
	}
	w.file = file
	w.day = day
	return nil
}
