package handler

import (
	"log"
	"net/http"
	"time"

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

// listChannels returns cached channels from all adapters (groups + friends).
// GET /api/v1/channels
func (h *BridgeHandler) listChannels(w http.ResponseWriter, r *http.Request) {
	h.channelsMu.RLock()
	channels := h.cachedChannels
	h.channelsMu.RUnlock()
	if channels == nil {
		channels = []bridge.ChannelInfo{}
	}
	writeJSON(w, http.StatusOK, map[string]interface{}{
		"channels": channels,
		"total":    len(channels),
	})
}

// StartChannelRefresh periodically queries all adapters for their channel lists.
func (h *BridgeHandler) StartChannelRefresh(interval time.Duration) {
	if interval <= 0 {
		interval = 10 * time.Minute
	}
	go func() {
		ticker := time.NewTicker(interval)
		defer ticker.Stop()
		log.Printf("[channel-refresh] 频道缓存刷新已启动 (间隔=%v)", interval)
		h.refreshChannels()
		for range ticker.C {
			h.refreshChannels()
		}
	}()
}

// refreshChannels queries all ChannelLister adapters and updates the cache.
func (h *BridgeHandler) refreshChannels() {
	var all []bridge.ChannelInfo
	for _, name := range h.router.ListAdapters() {
		a, err := h.router.GetAdapter(name)
		if err != nil {
			continue
		}
		if lister, ok := a.(bridge.ChannelLister); ok {
			channels := lister.ListChannels()
			all = append(all, channels...)
		}
	}
	h.channelsMu.Lock()
	h.cachedChannels = all
	h.channelsMu.Unlock()
	log.Printf("[channel-refresh] 频道缓存已更新: %d 个频道", len(all))
}
