package controllers

import (
	"errors"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/shared"
)

func ListBuyers(c *gin.Context) {
	// Get limit and offset from query parameter with defaults
	limitStr := c.DefaultQuery("limit", "99999999999999999999999999999999")
	offsetStr := c.DefaultQuery("offset", "0")

	// Convert limit and offset to int
	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		log.Printf("ListBuyers Error: Invalid limit value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid limit value"})
		return
	}

	offset, err := strconv.Atoi(offsetStr)
	if err != nil {
		log.Printf("ListBuyers Error: Invalid offset value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid offset value"})
		return
	}

	// Create a slice to hold the buyers
	var buyers []models.Buyer

	// Count the total number of buyers
	var total int64
	if err := shared.GetDb().Model(&models.Buyer{}).Count(&total).Error; err != nil {
		log.Printf("ListBuyers Error: Database error: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
		return
	}

	// Fetch the buyers from the database with LIMIT and OFFSET
	if err := shared.GetDb().Order("created_at desc").Limit(limit).Offset(offset).Find(&buyers).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Printf("ListBuyers Error: No buyers found: %v", err)
			c.JSON(http.StatusNotFound, gin.H{"error": "No buyers found"})
		} else {
			log.Printf("ListBuyers Error: Database error: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
		}
		return
	}

	// Respond with the buyers and the total count
	c.JSON(http.StatusOK, gin.H{"total": total, "buyers": buyers})
}
