package systemconfig

import (
	"errors"
	"net/http"

	"hfb_sys/backend/internal/middleware"
	"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 (h *Handler) List(c *gin.Context) {
	items, err := h.service.List()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, gin.H{"items": items})
}

func (h *Handler) PublishOptions(c *gin.Context) {
	options, err := h.service.PublishOptions()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, options)
}

func (h *Handler) SalePriceConfig(c *gin.Context) {
	config, err := h.service.SalePriceConfig()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, config)
}

func (h *Handler) OrderAgreements(c *gin.Context) {
	agreements, err := h.service.OrderAgreements()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, agreements)
}

func (h *Handler) PostRentalNotice(c *gin.Context) {
	notice, err := h.service.PostRentalNotice()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, notice)
}

func (h *Handler) HomeAnnouncements(c *gin.Context) {
	announcements, err := h.service.HomeAnnouncements()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, announcements)
}

func (h *Handler) HomeConfig(c *gin.Context) {
	config, err := h.service.HomeConfig()
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, config)
}

func (h *Handler) Update(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	key := c.Param("key")
	var req UpdateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "配置值不能为空")
		return
	}
	item, err := h.service.Update(adminID, key, req, auditMeta(c))
	if err != nil {
		writeConfigError(c, err)
		return
	}
	response.OK(c, item)
}

func auditMeta(c *gin.Context) AuditMeta {
	return AuditMeta{
		IP:        c.ClientIP(),
		UserAgent: c.GetHeader("User-Agent"),
		RequestID: middleware.GetRequestID(c),
	}
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}

func writeConfigError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrInvalidConfig):
		response.BadRequest(c, "配置不符合规则")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "系统配置服务暂时不可用")
	}
}
