package adminaudit

import (
	"errors"
	"net/http"
	"strconv"

	"hfb_sys/backend/pkg/response"

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

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

func parsePagination(c *gin.Context) (int, int) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	return page, pageSize
}

func (h *Handler) List(c *gin.Context) {
	query, ok := parseQuery(c)
	if !ok {
		return
	}
	result, err := h.service.List(query)
	if err != nil {
		writeAuditError(c, err)
		return
	}
	response.OK(c, result)
}

func parseQuery(c *gin.Context) (Query, bool) {
	var query Query
	if raw := c.Query("actor_id"); raw != "" {
		value, err := strconv.ParseUint(raw, 10, 64)
		if err != nil || value == 0 {
			response.BadRequest(c, "管理员 ID 不正确")
			return query, false
		}
		query.ActorID = value
	}
	query.Action = c.Query("action")
	query.BizType = c.Query("biz_type")
	page, pageSize := parsePagination(c)
	query.Page = page
	query.PageSize = pageSize
	return query, true
}

func writeAuditError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "审计日志服务暂时不可用")
	}
}
