package eventlogger

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sync"

	"git.warky.dev/wdevs/whatshooked/pkg/events"
)

// FileTarget logs events to organized file structure
type FileTarget struct {
	baseDir string
	mu      sync.Mutex
}

// NewFileTarget creates a new file-based logging target
func NewFileTarget(baseDir string) (*FileTarget, error) {
	// Create base directory if it doesn't exist
	if err := os.MkdirAll(baseDir, 0755); err != nil {
		return nil, fmt.Errorf("failed to create event log directory: %w", err)
	}

	return &FileTarget{
		baseDir: baseDir,
	}, nil
}

// Log writes an event to a file
func (ft *FileTarget) Log(event events.Event) error {
	ft.mu.Lock()
	defer ft.mu.Unlock()

	// Create directory structure: baseDir/[type]/[YYYYMMDD]/
	eventType := string(event.Type)
	dateDir := event.Timestamp.Format("20060102")
	dirPath := filepath.Join(ft.baseDir, eventType, dateDir)

	if err := os.MkdirAll(dirPath, 0755); err != nil {
		return fmt.Errorf("failed to create event directory: %w", err)
	}

	// Create filename: [hh24_mi_ss]_[type].json
	filename := fmt.Sprintf("%s_%s.json",
		event.Timestamp.Format("15_04_05"),
		eventType,
	)
	filePath := filepath.Join(dirPath, filename)

	// Marshal event to JSON
	data, err := json.MarshalIndent(event, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal event: %w", err)
	}

	// Write to file
	if err := os.WriteFile(filePath, data, 0644); err != nil {
		return fmt.Errorf("failed to write event file: %w", err)
	}

	return nil
}

// Close closes the file target (no-op for file target)
func (ft *FileTarget) Close() error {
	return nil
}
