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 CreateParkingLot(c *gin.Context) {
	var req request.ParkingLotCreate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

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

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

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

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

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

	lot, err := ParkingLotService.GetParkingLotByID(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(lot, c)
}

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

	lot, err := ParkingLotService.GetParkingLotByCode(code)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(lot, c)
}

func QueryAllParkingLots(c *gin.Context) {
	lots, err := ParkingLotService.QueryAllParkingLots()
	if err != nil {
		response.FailWithMessage("THE QUERY FAILED", c)
		return
	}
	response.OkWithData(lots, c)
}

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

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

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

func DeleteParkingLot(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 = ParkingLotService.DeleteParkingLot(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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