package handlers

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"fishfish/database"
	"fishfish/models"
)

func CreateOrder(c *gin.Context) {
	userID := getUserID(c)

	var req struct {
		DeliveryAddress string `json:"delivery_address" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Не указан адрес доставки"})
		return
	}

	var cartItems []models.CartItem
	if err := database.DB.Preload("Item").Where("user_id = ? ", userID).Find(&cartItems).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Не удалось получить корзину"})
		return
	}

	if len(cartItems) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Корзина пуста"})
		return
	}

	var order models.Order
	err := database.DB.Transaction(func(tx *gorm.DB) error {
		var total float64
		var orderItems []models.OrderItem

		for _, cartItem := range cartItems {
			item := cartItem.Item

			result := tx.Model(&models.Item{}).Where("id = ? AND stock >= ?", item.ID, cartItem.Quantity).Update("stock", gorm.Expr("stock - ? ", cartItem.Quantity))

			if result.RowsAffected == 0 {
				return fmt.Errorf("Недостаточно товара '%s' на складе", item.Name)
			}

			itemTotal := float64(item.Price) * cartItem.Quantity
			total += itemTotal

			orderItems = append(orderItems, models.OrderItem{
				ItemID:   cartItem.ItemID,
				Quantity: cartItem.Quantity,
				Price:    float64(item.Price),
			})
		}

		order = models.Order{
			UserID:          userID,
			Status:          "new",
			DeliveryAddress: req.DeliveryAddress,
			TotalPrice:      total,
			Items:           orderItems,
		}

		if err := tx.Create(&order).Error; err != nil {
			return err
		}

		if err := tx.Where("user_id = ? ", userID).Delete(&models.CartItem{}).Error; err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, order)
}
