package routes

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

	"github.com/break/junhong_cmp_fiber/internal/handler/admin"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
	"github.com/break/junhong_cmp_fiber/pkg/openapi"
)

func registerWechatConfigRoutes(router fiber.Router, handler *admin.WechatConfigHandler, doc *openapi.Generator, basePath string) {
	// 平台用户权限中间件：仅超级管理员和平台用户可访问支付配置管理
	group := router.Group("/wechat-configs", func(c *fiber.Ctx) error {
		userType := middleware.GetUserTypeFromContext(c.UserContext())
		if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
			return errors.New(errors.CodeForbidden, "无权限访问支付配置管理功能")
		}
		return c.Next()
	})
	groupPath := basePath + "/wechat-configs"

	// active 路由必须在 /:id 之前注册，否则 "active" 会被当作 id 解析
	Register(group, doc, groupPath, "GET", "/active", handler.GetActive, RouteSpec{
		Summary: "获取当前生效的支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   nil,
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "GET", "", handler.List, RouteSpec{
		Summary: "获取支付配置列表",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.WechatConfigListRequest),
		Output:  new(dto.WechatConfigListResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "POST", "", handler.Create, RouteSpec{
		Summary: "创建支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.CreateWechatConfigRequest),
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "GET", "/:id", handler.Get, RouteSpec{
		Summary: "获取支付配置详情",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.IDReq),
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "PUT", "/:id", handler.Update, RouteSpec{
		Summary: "更新支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.UpdateWechatConfigParams),
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "DELETE", "/:id", handler.Delete, RouteSpec{
		Summary: "删除支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.IDReq),
		Output:  nil,
		Auth:    true,
	})

	Register(group, doc, groupPath, "POST", "/:id/activate", handler.Activate, RouteSpec{
		Summary: "激活支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.IDReq),
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})

	Register(group, doc, groupPath, "POST", "/:id/deactivate", handler.Deactivate, RouteSpec{
		Summary: "停用支付配置",
		Tags:    []string{"微信支付配置管理"},
		Input:   new(dto.IDReq),
		Output:  new(dto.WechatConfigResponse),
		Auth:    true,
	})
}
