package controllers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gitlab.com/pactual1/backend/database/invoice"
)

func GetInvoices(c *gin.Context) {
	limitStr := c.DefaultQuery("limit", "10")
	offsetStr := c.DefaultQuery("offset", "0")
	buyerName := c.Query("buyer_name")
	sortBy := c.Query("sort_by")

	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid limit value"})
		return
	}

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

	invoices, total, err := invoice.GetInvoices(buyerName, sortBy, limit, offset, 0)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"total": total, "invoices": invoices})
}

func GetInvoiceByID(c *gin.Context) {
    idStr := c.Param("id")
    id, err := strconv.Atoi(idStr)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
        return
    }

    invoices, _, err := invoice.GetInvoices("", "", 1, 0, uint(id))
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    if len(invoices) > 0 {
        c.JSON(http.StatusOK, gin.H{"invoice": invoices[0]})
    } else {
        c.JSON(http.StatusNotFound, gin.H{"error": "Invoice not found"})
    }
}

