package handler

import (
	"net/http"
	"strconv"

	"git.yeij.top/AskaEth/Cyrene/platform-bridge/internal/config"
	"git.yeij.top/AskaEth/Cyrene/platform-bridge/internal/logging"
)

// LogHandler exposes message log retrieval endpoints.
type LogHandler struct {
	logger *logging.Logger
	store  *config.Store
}

func NewLogHandler(logger *logging.Logger, store *config.Store) *LogHandler {
	return &LogHandler{logger: logger, store: store}
}

func (h *LogHandler) RegisterRoutes(mux *http.ServeMux) {
	mux.HandleFunc("/api/v1/logs/", h.handleLogs)
}

func (h *LogHandler) handleLogs(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Path[len("/api/v1/logs/"):]
	if name == "" {
		writeJSON(w, http.StatusBadRequest, errResp("missing platform name in path"))
		return
	}

	// Resolve platform type from config name (e.g. "obv11-home" → "obv11").
	platform := name
	if h.store != nil {
		if cfg, err := h.store.Get(name); err == nil && cfg.Platform != "" {
			platform = cfg.Platform
		}
	}

	limit := 100
	if l := r.URL.Query().Get("limit"); l != "" {
		if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 1000 {
			limit = n
		}
	}

	entries, err := h.logger.ReadLogs(platform, limit)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
		return
	}
	if entries == nil {
		entries = []logging.LogEntry{}
	}
	writeJSON(w, http.StatusOK, map[string]interface{}{
		"platform": platform,
		"total":    len(entries),
		"logs":     entries,
	})
}
