package payment

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

var vehicleSvc = service.ServiceGroupApp.VehicleServiceGroup.VehicleService
var paymentSvc = paymentService.NewPaymentService()

// ExitPreview 费用预览（只读，不修改数据库）
func ExitPreview(c *gin.Context) {
	var req request.VehicleEntry
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	resp, err := vehicleSvc.ExitPreview(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(resp, c)
}

// ExitConfirm 确认出场 + 支付
func ExitConfirm(c *gin.Context) {
	var req request.ExitConfirmRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	resp, err := vehicleSvc.ExitConfirm(req, utils.GetUserID(c))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(resp, c)
}

// ListPayments 收费记录列表
func ListPayments(c *gin.Context) {
	var q repository.PaymentListQuery
	if err := c.ShouldBindQuery(&q); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := paymentSvc.QueryPayments(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)
}

// TodaySummary 当日收费汇总
func TodaySummary(c *gin.Context) {
	s, err := paymentSvc.GetTodaySummary()
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(s, c)
}

// SetupPaymentRouter 注册支付相关路由
func SetupPaymentRouter(router *gin.RouterGroup) {
	pg := router.Group("/payment")
	{
		pg.GET("/list", ListPayments)
		pg.GET("/today-summary", TodaySummary)
	}
	eg := router.Group("/vehicle")
	{
		eg.POST("/exit/preview", ExitPreview)
		eg.POST("/exit/confirm", ExitConfirm)
	}
}
