package writer

import (
	"encoding/json"
	"log"
	"os"
	"sync"

	"git.krilio.net/nuno/wgctl-conntrack/conntrack"
)

// LogWriter writes TrafficEvents as JSON lines to a file
type LogWriter struct {
	path string
	mu   sync.Mutex
}

func NewLogWriter(path string) *LogWriter {
	return &LogWriter{path: path}
}

func (w *LogWriter) Write(ev conntrack.TrafficEvent) error {
	w.mu.Lock()
	defer w.mu.Unlock()

	f, err := os.OpenFile(w.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer f.Close()

	data, err := json.Marshal(ev)
	if err != nil {
		return err
	}

	_, err = f.Write(append(data, '\n'))
	return err
}

func (w *LogWriter) Run(events <-chan conntrack.TrafficEvent) {
	for ev := range events {
		if err := w.Write(ev); err != nil {
			log.Printf("error writing event: %v", err)
		}
	}
}