package policyconfig

import (
	"database/sql"
	"fmt"
	"strconv"
	"strings"

	"hyapp-admin-server/internal/appctx"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/response"

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

type Handler struct {
	service *Service
	audit   shared.OperationLogger
}

func New(adminDB *sql.DB, walletDB *sql.DB, userDB *sql.DB, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(adminDB, walletDB, userDB), audit: audit}
}

func (h *Handler) ListTemplates(c *gin.Context) {
	options := shared.ListOptions(c)
	items, total, err := h.service.ListTemplates(c.Request.Context(), listTemplatesQuery{
		Keyword:  strings.TrimSpace(options.Keyword),
		Status:   strings.TrimSpace(options.Status),
		Page:     options.Page,
		PageSize: options.PageSize,
	})
	if err != nil {
		response.ServerError(c, "获取 POINT 钱包政策失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) CreateTemplate(c *gin.Context) {
	var req templateRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "POINT 钱包政策参数不正确")
		return
	}
	item, err := h.service.CreateTemplate(c.Request.Context(), shared.ActorFromContext(c).UserID, req)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "create-policy-template", "admin_policy_templates", item.TemplateCode+":"+item.TemplateVersion, "success", item.Name)
	response.Created(c, item)
}

func (h *Handler) ListInstances(c *gin.Context) {
	options := shared.ListOptions(c)
	items, total, err := h.service.ListInstances(c.Request.Context(), appctx.FromContext(c.Request.Context()), listInstancesQuery{
		Keyword:  strings.TrimSpace(options.Keyword),
		Status:   strings.TrimSpace(options.Status),
		Page:     options.Page,
		PageSize: options.PageSize,
	})
	if err != nil {
		response.ServerError(c, "获取 POINT 钱包政策实例失败")
		return
	}
	response.OK(c, response.Page{Items: items, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) CreateInstance(c *gin.Context) {
	var req instanceRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "POINT 钱包政策实例参数不正确")
		return
	}
	item, err := h.service.CreateInstance(c.Request.Context(), appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, req)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "create-policy-instance", "admin_policy_instances", strconv.FormatUint(item.InstanceID, 10), "success", fmt.Sprintf("app_code=%s", item.AppCode))
	response.Created(c, item)
}

func (h *Handler) PublishInstance(c *gin.Context) {
	instanceID, ok := parseUintParam(c, "instance_id")
	if !ok {
		return
	}
	result, err := h.service.PublishInstance(c.Request.Context(), appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, instanceID)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "publish-policy-instance", "admin_policy_instances", strconv.FormatUint(instanceID, 10), "success", fmt.Sprintf("targets=%d", result.TargetCount))
	response.OK(c, result)
}

func (h *Handler) UpdateInstanceStatus(c *gin.Context) {
	instanceID, ok := parseUintParam(c, "instance_id")
	if !ok {
		return
	}
	var req statusRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "POINT 钱包政策实例状态参数不正确")
		return
	}
	item, err := h.service.UpdateInstanceStatus(c.Request.Context(), appctx.FromContext(c.Request.Context()), shared.ActorFromContext(c).UserID, instanceID, req.Status)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLogWithResourceID(c, h.audit, "update-policy-instance-status", "admin_policy_instances", strconv.FormatUint(instanceID, 10), "success", item.Status)
	response.OK(c, item)
}

func parseUintParam(c *gin.Context, key string) (uint64, bool) {
	value := strings.TrimSpace(c.Param(key))
	parsed, err := strconv.ParseUint(value, 10, 64)
	if err != nil || parsed == 0 {
		response.BadRequest(c, "ID 参数不正确")
		return 0, false
	}
	return parsed, true
}
