package app

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/service/red_packet_service"
	"bwallet/validate_service"
	"github.com/gin-gonic/gin"
	"strings"
)

func AddRedPacket(c *gin.Context) {
	red_packet := validate_service.RedPacket{}
	c.ShouldBindJSON(&red_packet)

	if ok, errors := validate_service.ValidateInputs(red_packet); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	RedPacketService := red_packet_service.RedPacket{
		PacketId: red_packet.PacketId,
		LiveId:   red_packet.LiveId,
		Avatar:   red_packet.Avatar,
	}
	exist, err := RedPacketService.ExistByPacketInfoId()
	if err != nil {
		handler.SendResponse(c, errno.ErrAddRedPacket, nil)
		return
	}
	if exist {
		handler.SendResponse(c, errno.ErrExistRedPacket, nil)
		return
	}
	if err := RedPacketService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrAddRedPacket, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}

func GetRedPackets(c *gin.Context) {
	red_packet := validate_service.RedPacketReq{}
	c.ShouldBindJSON(&red_packet)

	if ok, errors := validate_service.ValidateInputs(red_packet); !ok {
		for _, err := range errors {
			handler.SendResponse(c, errno.ErrBind, strings.Join(err, " "))
			return
		}
	}

	RedPacketService := red_packet_service.RedPacket{
		LiveId: int32(red_packet.LiveId),
		UserId: red_packet.UserId,
		Status: 1,
	}

	info, err := RedPacketService.GetRedPackets()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = info
	data["total"] = len(info)

	handler.SendResponse(c, nil, data)
}
