package vehicle

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

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

// CreateVehicleType 创建车辆类型
func CreateVehicleType(c *gin.Context) {
	var req request.VehicleTypeCreate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err := vehicleTypeService.CreateVehicleType(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

// UpdateVehicleType 更新车辆类型
func UpdateVehicleType(c *gin.Context) {
	var req request.VehicleTypeUpdate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

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

// GetVehicleTypeByID 根据ID获取车辆类型
func GetVehicleTypeByID(c *gin.Context) {
	id := c.Query("id")
	uintID := uint(0)
	_, err := fmt.Sscanf(id, "%d", &uintID)
	if err != nil {
		response.FailWithMessage("无效的ID", c)
		return
	}

	vehicleTypeInfo, err := vehicleTypeService.GetVehicleTypeByID(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(vehicleTypeInfo, c)
}

// ListVehicleTypes 获取车辆类型列表
func ListVehicleTypes(c *gin.Context) {
	var info request.VehicleTypeQuery
	if err := c.ShouldBindJSON(&info); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	total, list, err := vehicleTypeService.ListVehicleTypes(info)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     info.Page,
		PageSize: info.PageSize,
	}, "获取成功", c)
}

// DeleteVehicleType 删除车辆类型
func DeleteVehicleType(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 = vehicleTypeService.DeleteVehicleType(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

// GetAllVehicleTypes 获取所有车辆类型（用于下拉选择）
func GetAllVehicleTypes(c *gin.Context) {
	vehicleTypes, err := vehicleTypeService.GetAllVehicleTypes()
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(vehicleTypes, c)
}
