package parking

import (
	"fmt"
	"wails-app/internal/model/common/response"
	"wails-app/internal/model/parking/request"
	parkingResponse "wails-app/internal/model/parking/response"

	"github.com/gin-gonic/gin"
)

func CreateChannel(c *gin.Context) {
	var req request.ChannelCreate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err := ChannelService.CreateChannel(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("创建成功", c)
}

func UpdateChannel(c *gin.Context) {
	var req request.ChannelUpdate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err := ChannelService.UpdateChannel(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("更新成功", c)
}

func GetChannelByID(c *gin.Context) {
	id := c.Query("id")
	uintID := uint(0)
	_, err := fmt.Sscanf(id, "%d", &uintID)
	if err != nil {
		response.FailWithMessage("无效的ID", c)
		return
	}

	channel, err := ChannelService.GetChannelByID(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(channel, c)
}

func GetChannelByCode(c *gin.Context) {
	code := c.Query("code")
	if code == "" {
		response.FailWithMessage("通道编码不能为空", c)
		return
	}

	channel, err := ChannelService.GetChannelByCode(code)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(channel, c)
}

func QueryAllChannels(c *gin.Context) {
	channels, err := ChannelService.QueryAllChannels()
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithData(channels, c)
}

func ListChannels(c *gin.Context) {
	var req request.ChannelQuery
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	total, list, err := ChannelService.ListChannels(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(parkingResponse.ChannelList{
		Total: total,
		List:  list,
	}, c)
}

func DeleteChannel(c *gin.Context) {
	id := c.Query("id")
	uintID := uint(0)
	_, err := fmt.Sscanf(id, "%d", &uintID)
	if err != nil {
		response.FailWithMessage("无效的ID", c)
		return
	}

	err = ChannelService.DeleteChannel(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("删除成功", c)
}
