// Filename: internal/handlers/log_handler.go
package handlers

import (
	"gemini-balancer/internal/errors"
	"gemini-balancer/internal/response"
	"gemini-balancer/internal/service"

	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

type LogHandler struct {
	logService *service.LogService
}

func NewLogHandler(logService *service.LogService) *LogHandler {
	return &LogHandler{logService: logService}
}

func (h *LogHandler) GetLogs(c *gin.Context) {
	queryParams := make(map[string]string)
	for key, values := range c.Request.URL.Query() {
		if len(values) > 0 {
			queryParams[key] = values[0]
		}
	}
	params, err := service.ParseLogQueryParams(queryParams)
	if err != nil {
		response.Error(c, errors.ErrBadRequest)
		return
	}
	logs, total, err := h.logService.GetLogs(c.Request.Context(), params)
	if err != nil {
		response.Error(c, errors.ErrDatabase)
		return
	}
	response.Success(c, gin.H{
		"items":     logs,
		"total":     total,
		"page":      params.Page,
		"page_size": params.PageSize,
	})
}

// DeleteLogs 删除选定日志 DELETE /admin/logs?ids=1,2,3
func (h *LogHandler) DeleteLogs(c *gin.Context) {
	idsStr := c.Query("ids")
	if idsStr == "" {
		response.Error(c, errors.ErrBadRequest)
		return
	}

	var ids []uint
	for _, idStr := range strings.Split(idsStr, ",") {
		if id, err := strconv.ParseUint(strings.TrimSpace(idStr), 10, 32); err == nil {
			ids = append(ids, uint(id))
		}
	}

	if len(ids) == 0 {
		response.Error(c, errors.ErrBadRequest)
		return
	}

	if err := h.logService.DeleteLogs(c.Request.Context(), ids); err != nil {
		response.Error(c, errors.ErrDatabase)
		return
	}

	response.Success(c, gin.H{"deleted": len(ids)})
}

// DeleteAllLogs 删除全部日志 DELETE /admin/logs/all
func (h *LogHandler) DeleteAllLogs(c *gin.Context) {
	if err := h.logService.DeleteAllLogs(c.Request.Context()); err != nil {
		response.Error(c, errors.ErrDatabase)
		return
	}
	response.Success(c, gin.H{"message": "all logs deleted"})
}

// DeleteOldLogs 删除旧日志 DELETE /admin/logs/old?days=30
func (h *LogHandler) DeleteOldLogs(c *gin.Context) {
	daysStr := c.Query("days")
	days, err := strconv.Atoi(daysStr)
	if err != nil || days <= 0 {
		response.Error(c, errors.ErrBadRequest)
		return
	}

	deleted, err := h.logService.DeleteOldLogs(c.Request.Context(), days)
	if err != nil {
		response.Error(c, errors.ErrDatabase)
		return
	}

	response.Success(c, gin.H{"deleted": deleted, "days": days})
}
