package admin

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

	"github.com/break/junhong_cmp_fiber/internal/gateway"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	iotCardService "github.com/break/junhong_cmp_fiber/internal/service/iot_card"
	"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/response"
)

type IotCardHandler struct {
	service       *iotCardService.Service
	gatewayClient *gateway.Client
}

func NewIotCardHandler(service *iotCardService.Service, gatewayClient *gateway.Client) *IotCardHandler {
	return &IotCardHandler{
		service:       service,
		gatewayClient: gatewayClient,
	}
}

func (h *IotCardHandler) ListStandalone(c *fiber.Ctx) error {
	var req dto.ListStandaloneIotCardRequest
	if err := c.QueryParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	result, err := h.service.ListStandalone(c.UserContext(), &req)
	if err != nil {
		return err
	}

	return response.SuccessWithPagination(c, result.List, result.Total, result.Page, result.PageSize)
}

func (h *IotCardHandler) GetByICCID(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	result, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *IotCardHandler) AllocateCards(c *fiber.Ctx) error {
	var req dto.AllocateStandaloneCardsRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	ctx := c.UserContext()
	operatorID := middleware.GetUserIDFromContext(ctx)
	userType := middleware.GetUserTypeFromContext(ctx)

	var operatorShopID *uint
	if userType == constants.UserTypeAgent {
		shopID := middleware.GetShopIDFromContext(ctx)
		if shopID > 0 {
			operatorShopID = &shopID
		}
	}

	result, err := h.service.AllocateCards(ctx, &req, operatorID, operatorShopID)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *IotCardHandler) RecallCards(c *fiber.Ctx) error {
	var req dto.RecallStandaloneCardsRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	ctx := c.UserContext()
	operatorID := middleware.GetUserIDFromContext(ctx)
	userType := middleware.GetUserTypeFromContext(ctx)

	var operatorShopID *uint
	if userType == constants.UserTypeAgent {
		shopID := middleware.GetShopIDFromContext(ctx)
		if shopID > 0 {
			operatorShopID = &shopID
		}
	}

	result, err := h.service.RecallCards(ctx, &req, operatorID, operatorShopID)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

func (h *IotCardHandler) BatchSetSeriesBinding(c *fiber.Ctx) error {
	var req dto.BatchSetCardSeriesBindngRequest
	if err := c.BodyParser(&req); err != nil {
		return errors.New(errors.CodeInvalidParam, "请求参数解析失败")
	}

	ctx := c.UserContext()
	userType := middleware.GetUserTypeFromContext(ctx)

	var operatorShopID *uint
	if userType == constants.UserTypeAgent {
		shopID := middleware.GetShopIDFromContext(ctx)
		if shopID > 0 {
			operatorShopID = &shopID
		}
	}

	result, err := h.service.BatchSetSeriesBinding(ctx, &req, operatorShopID)
	if err != nil {
		return err
	}

	return response.Success(c, result)
}

// GetGatewayStatus 查询卡实时状态
func (h *IotCardHandler) GetGatewayStatus(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	resp, err := h.gatewayClient.QueryCardStatus(c.UserContext(), &gateway.CardStatusReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, resp)
}

// GetGatewayFlow 查询流量使用情况
func (h *IotCardHandler) GetGatewayFlow(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	resp, err := h.gatewayClient.QueryFlow(c.UserContext(), &gateway.FlowQueryReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, resp)
}

// GetGatewayRealname 查询实名认证状态
func (h *IotCardHandler) GetGatewayRealname(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	resp, err := h.gatewayClient.QueryRealnameStatus(c.UserContext(), &gateway.CardStatusReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, resp)
}

// GetRealnameLink 获取实名认证链接
func (h *IotCardHandler) GetRealnameLink(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	link, err := h.gatewayClient.GetRealnameLink(c.UserContext(), &gateway.CardStatusReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, link)
}

// StopCard 停止卡服务
func (h *IotCardHandler) StopCard(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	err = h.gatewayClient.StopCard(c.UserContext(), &gateway.CardOperationReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, nil)
}

// StartCard 恢复卡服务
func (h *IotCardHandler) StartCard(c *fiber.Ctx) error {
	iccid := c.Params("iccid")
	if iccid == "" {
		return errors.New(errors.CodeInvalidParam, "ICCID不能为空")
	}

	// 验证权限：查询数据库确认卡存在且用户有权限访问
	_, err := h.service.GetByICCID(c.UserContext(), iccid)
	if err != nil {
		return errors.New(errors.CodeNotFound, "卡不存在或无权限访问")
	}

	// 调用 Gateway
	err = h.gatewayClient.StartCard(c.UserContext(), &gateway.CardOperationReq{
		CardNo: iccid,
	})
	if err != nil {
		return err
	}

	return response.Success(c, nil)
}
