package owner

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"wails-app/internal/model/common/response"
	"wails-app/internal/model/owner/request"
	ownerResponse "wails-app/internal/model/owner/response"
	"wails-app/internal/service/owner"
)

// CreateOwner 创建车主信息
func CreateOwner(c *gin.Context) {
	var req request.OwnerCreate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err := owner.OwnerService.CreateOwner(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

// UpdateOwner 更新车主信息
func UpdateOwner(c *gin.Context) {
	var req request.OwnerUpdate
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	err := owner.OwnerService.UpdateOwner(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

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

	ownerInfo, err := owner.OwnerService.GetOwnerByID(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(ownerInfo, c)
}

// GetOwnerByPhone 根据手机号获取车主信息
func GetOwnerByPhone(c *gin.Context) {
	phone := c.Query("phone")
	if phone == "" {
		response.FailWithMessage("手机号不能为空", c)
		return
	}

	ownerInfo, err := owner.OwnerService.GetOwnerByPhone(phone)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithData(ownerInfo, c)
}

// ListOwners 获取车主列表
func ListOwners(c *gin.Context) {
	var req request.OwnerQuery
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

	response.OkWithData(ownerResponse.OwnerList{
		Total: total,
		List:  list,
	}, c)
}

// DeleteOwner 删除车主
func DeleteOwner(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 = owner.OwnerService.DeleteOwner(uintID)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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