package shift

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

var shiftSvc = service.NewShiftService()

type startReq struct {
	StartingCash float64 `json:"starting_cash"`
}

type endReq struct {
	ActualCash float64 `json:"actual_cash"`
	Remark     string  `json:"remark"`
}

func StartShift(c *gin.Context) {
	var req startReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	rec, err := shiftSvc.Start(utils.GetUserID(c), req.StartingCash)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(rec, c)
}

func EndShift(c *gin.Context) {
	var req endReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	rec, err := shiftSvc.End(utils.GetUserID(c), req.ActualCash, req.Remark)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(rec, c)
}

func GetCurrentShift(c *gin.Context) {
	rec, err := shiftSvc.GetCurrent(utils.GetUserID(c))
	if err != nil {
		response.FailWithMessage("无当班", c)
		return
	}
	response.OkWithData(rec, c)
}

func ListShifts(c *gin.Context) {
	var q repository.ShiftListQuery
	if err := c.ShouldBindQuery(&q); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := shiftSvc.List(q, utils.GetUserID(c))
	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 SetupShiftRouter(router *gin.RouterGroup) {
	sr := router.Group("/shift")
	sr.POST("/start", StartShift)
	sr.POST("/end", EndShift)
	sr.GET("/current", GetCurrentShift)
	sr.GET("/list", ListShifts)
}
