package admin

import (
	"github.com/gofiber/fiber/v2"

	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/internal/service/polling"
	"github.com/break/junhong_cmp_fiber/pkg/response"
)

// PollingMonitoringHandler 轮询监控处理器
type PollingMonitoringHandler struct {
	service *polling.MonitoringService
}

// NewPollingMonitoringHandler 创建轮询监控处理器
func NewPollingMonitoringHandler(service *polling.MonitoringService) *PollingMonitoringHandler {
	return &PollingMonitoringHandler{service: service}
}

// GetOverview 获取轮询总览
// @Summary 获取轮询总览统计
// @Description 获取轮询系统的总览统计数据，包括初始化进度、队列大小等
// @Tags 轮询管理-监控
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=dto.PollingOverviewResp}
// @Router /api/admin/polling-stats [get]
func (h *PollingMonitoringHandler) GetOverview(c *fiber.Ctx) error {
	ctx := c.UserContext()

	stats, err := h.service.GetOverview(ctx)
	if err != nil {
		return err
	}

	return response.Success(c, &dto.PollingOverviewResp{
		TotalCards:        stats.TotalCards,
		InitializedCards:  stats.InitializedCards,
		InitProgress:      stats.InitProgress,
		IsInitializing:    stats.IsInitializing,
		RealnameQueueSize: stats.RealnameQueueSize,
		CarddataQueueSize: stats.CarddataQueueSize,
		PackageQueueSize:  stats.PackageQueueSize,
	})
}

// GetQueueStatuses 获取队列状态
// @Summary 获取轮询队列状态
// @Description 获取所有轮询队列的详细状态，包括队列大小、到期数、等待时间等
// @Tags 轮询管理-监控
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=dto.PollingQueueStatusListResp}
// @Router /api/admin/polling-stats/queues [get]
func (h *PollingMonitoringHandler) GetQueueStatuses(c *fiber.Ctx) error {
	ctx := c.UserContext()

	statuses, err := h.service.GetQueueStatuses(ctx)
	if err != nil {
		return err
	}

	items := make([]*dto.PollingQueueStatusResp, 0, len(statuses))
	for _, s := range statuses {
		items = append(items, &dto.PollingQueueStatusResp{
			TaskType:      s.TaskType,
			TaskTypeName:  s.TaskTypeName,
			QueueSize:     s.QueueSize,
			ManualPending: s.ManualPending,
			DueCount:      s.DueCount,
			AvgWaitTime:   s.AvgWaitTime,
		})
	}

	return response.Success(c, &dto.PollingQueueStatusListResp{Items: items})
}

// GetTaskStatuses 获取任务统计
// @Summary 获取轮询任务统计
// @Description 获取所有轮询任务类型的执行统计，包括成功率、平均耗时等
// @Tags 轮询管理-监控
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=dto.PollingTaskStatsListResp}
// @Router /api/admin/polling-stats/tasks [get]
func (h *PollingMonitoringHandler) GetTaskStatuses(c *fiber.Ctx) error {
	ctx := c.UserContext()

	statuses, err := h.service.GetTaskStatuses(ctx)
	if err != nil {
		return err
	}

	items := make([]*dto.PollingTaskStatsResp, 0, len(statuses))
	for _, s := range statuses {
		items = append(items, &dto.PollingTaskStatsResp{
			TaskType:       s.TaskType,
			TaskTypeName:   s.TaskTypeName,
			SuccessCount1h: s.SuccessCount1h,
			FailureCount1h: s.FailureCount1h,
			TotalCount1h:   s.TotalCount1h,
			SuccessRate:    s.SuccessRate,
			AvgDurationMs:  s.AvgDurationMs,
		})
	}

	return response.Success(c, &dto.PollingTaskStatsListResp{Items: items})
}

// GetInitProgress 获取初始化进度
// @Summary 获取轮询初始化进度
// @Description 获取轮询系统初始化的详细进度，包括已处理数、预计完成时间等
// @Tags 轮询管理-监控
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {object} response.Response{data=dto.PollingInitProgressResp}
// @Router /api/admin/polling-stats/init-progress [get]
func (h *PollingMonitoringHandler) GetInitProgress(c *fiber.Ctx) error {
	ctx := c.UserContext()

	progress, err := h.service.GetInitProgress(ctx)
	if err != nil {
		return err
	}

	return response.Success(c, &dto.PollingInitProgressResp{
		TotalCards:       progress.TotalCards,
		InitializedCards: progress.InitializedCards,
		Progress:         progress.Progress,
		IsComplete:       progress.IsComplete,
		StartedAt:        progress.StartedAt,
		EstimatedETA:     progress.EstimatedETA,
	})
}
