package controllers

import (
	dbConfig "ares/database/config"
	"ares/database/models"
	"strconv"

	"github.com/gofiber/fiber/v3"
)

// AdminContentCarts handles rendering the Carts list in the admin panel
func AdminContentCarts(c fiber.Ctx) error {
	var carts []models.Cart

	// Preload the User to display who owns the cart
	// Preload Items to show the item count
	query := dbConfig.DB.Model(&models.Cart{}).Preload("Items")

	// Filter by User ID if a search is provided (basic example, finding user by ID)
	search := c.Query("search")
	if search != "" {
		if userID, err := strconv.Atoi(search); err == nil {
			query = query.Where("user_id = ?", userID)
		}
	}

	query.Order("updated_at desc").Find(&carts)

	data := fiber.Map{
		"Carts":  carts,
		"Search": search,
	}

	// Render partial if requested via HTMX
	if c.Get("HX-Request") == "true" {
		return c.Render("admin/partials/carts", data)
	}

	// Otherwise render full layout
	return c.Render("admin/partials/carts", data, "admin/layout")
}

// AdminCartDelete handles deleting a cart (useful for clearing abandoned carts)
func AdminCartDelete(c fiber.Ctx) error {
	id := c.Params("id")

	if err := dbConfig.DB.Unscoped().Where("id = ?", id).Delete(&models.Cart{}).Error; err != nil {
		return c.Redirect().To("/admin/content/carts?error=Silme+başarısız")
	}

	return c.Redirect().To("/admin/content/carts?deleted=true&success=Sepet+silindi")
}
