package controllers

import (
	"catalogue.midpdsa.com/src/db/catalogue"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type VehicleBrandController struct {
	queries *catalogue.Queries
}

func NewVehicleBrandController(queries *catalogue.Queries) *VehicleBrandController {
	return &VehicleBrandController{queries: queries}
}

func (ctrl *VehicleBrandController) GetVehicleBrands(c *gin.Context) {
	limit, offset := parsePagination(c)
	search := parseSearch(c)
	brands, err := ctrl.queries.GetVehicleBrands(c.Request.Context(), catalogue.GetVehicleBrandsParams{Limit: limit, Offset: offset, Search: search})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, brands)
}

type CreateVehicleBrandRequest struct {
	Brand string `json:"brand" binding:"required"`
}

func (ctrl *VehicleBrandController) CreateVehicleBrand(c *gin.Context) {
	var req CreateVehicleBrandRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	brand, err := ctrl.queries.CreateVehicleBrand(c.Request.Context(), req.Brand)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, brand)
}

func (ctrl *VehicleBrandController) GetVehicleBrandById(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid brand id"})
		return
	}

	brand, err := ctrl.queries.GetVehicleBrandById(c.Request.Context(), int32(id))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "vehicle brand not found"})
		return
	}
	c.JSON(http.StatusOK, brand)
}

type UpdateVehicleBrandRequest struct {
	Brand string `json:"brand" binding:"required"`
}

func (ctrl *VehicleBrandController) UpdateVehicleBrand(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid brand id"})
		return
	}

	var req UpdateVehicleBrandRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	brand, err := ctrl.queries.UpdateVehicleBrand(c.Request.Context(), catalogue.UpdateVehicleBrandParams{
		ID:    int32(id),
		Brand: req.Brand,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, brand)
}

func (ctrl *VehicleBrandController) DeleteVehicleBrand(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid brand id"})
		return
	}

	if _, err := ctrl.queries.DeleteVehicleBrand(c.Request.Context(), int32(id)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "vehicle brand deleted"})
}
