package applog

import (
	"context"
	"sync"
	"time"

	"github.com/prism/proxy/internal/store"
)

type Entry struct {
	Level     string    `json:"level"`
	Source    string    `json:"source"`
	Message   string    `json:"message"`
	CreatedAt time.Time `json:"created_at"`
}

type Collector struct {
	mu      sync.RWMutex
	ring    []Entry
	cap     int
	store   *store.Store
	persist bool
}

func NewCollector(s *store.Store, capacity int, persist bool) *Collector {
	return &Collector{
		ring:    make([]Entry, 0, capacity),
		cap:     capacity,
		store:   s,
		persist: persist,
	}
}

func (c *Collector) Add(level, source, message string) {
	e := Entry{
		Level:     level,
		Source:    source,
		Message:   message,
		CreatedAt: time.Now(),
	}
	c.mu.Lock()
	if len(c.ring) >= c.cap {
		c.ring = c.ring[1:]
	}
	c.ring = append(c.ring, e)
	c.mu.Unlock()

	if c.persist && c.store != nil {
		_ = c.store.AddRequestLog(context.Background(), level, source, message)
	}
}

func (c *Collector) List(limit int) []Entry {
	c.mu.RLock()
	defer c.mu.RUnlock()
	if limit <= 0 || limit > len(c.ring) {
		limit = len(c.ring)
	}
	start := len(c.ring) - limit
	if start < 0 {
		start = 0
	}
	out := make([]Entry, limit)
	copy(out, c.ring[start:])
	return out
}
