package monthly

import (
	"strconv"

	"github.com/gin-gonic/gin"
	"wails-app/internal/model/common/response"
	"wails-app/internal/modules/monthly/repository"
	"wails-app/internal/modules/monthly/service"
	utils "wails-app/internal/pkg"
)

var monthlySvc = service.NewMonthlyCardService()

type createReq struct {
	VehicleID uint    `json:"vehicle_id"`
	CardType  string  `json:"card_type"`
	Fee       float64 `json:"fee"`
	Remark    string  `json:"remark"`
}

func CreateCard(c *gin.Context) {
	var req createReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	card, err := monthlySvc.Create(req.VehicleID, req.CardType, req.Fee, utils.GetUserID(c), req.Remark)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(card, c)
}

type renewReq struct {
	CardID   uint    `json:"card_id"`
	CardType string  `json:"card_type"`
	Fee      float64 `json:"fee"`
}

func RenewCard(c *gin.Context) {
	var req renewReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := monthlySvc.Renew(req.CardID, req.CardType, req.Fee, utils.GetUserID(c)); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("续费成功", c)
}

func RefundCard(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	if err := monthlySvc.Refund(uint(id)); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("退卡成功", c)
}

func ListCards(c *gin.Context) {
	var q repository.MonthlyCardQuery
	if err := c.ShouldBindQuery(&q); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := monthlySvc.List(q)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{List: list, Total: total, Page: q.Page, PageSize: q.PageSize}, "查询成功", c)
}

func SetupMonthlyCardRouter(router *gin.RouterGroup) {
	mc := router.Group("/monthly-card")
	{
		mc.POST("/create", CreateCard)
		mc.POST("/renew", RenewCard)
		mc.DELETE("/refund", RefundCard)
		mc.GET("/list", ListCards)
	}
}
