package invoice

import (
	"fmt"
	"strings"

	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/shared"
)

func GetInvoices(buyerName string, sortBy string, limit int, offset int, id uint) ([]models.Invoice, int64, error) {
    var invoices []models.Invoice

    // Default sort by InvoiceDate DESC
    sortField := "invoice_date"
    sortOrder := "desc"

    if sortBy == "InvoiceDate" || sortBy == "InvoiceDueDate" {
        sortField = strings.ToLower(sortBy)
    }

    dbOrder := fmt.Sprintf("%s %s", sortField, sortOrder)

    db := shared.GetDb()
    countDb := db

    if buyerName != "" {
        db = db.Where("buyer_name LIKE ?", "%"+buyerName+"%")
        countDb = countDb.Where("buyer_name LIKE ?", "%"+buyerName+"%")
    }

    // Added conditional for ID search
    if id != 0 {
        db = db.Where("id = ?", id)
        countDb = countDb.Where("id = ?", id)
    }

    var total int64
    if err := countDb.Model(&models.Invoice{}).Count(&total).Error; err != nil {
        return nil, 0, err
    }

    if err := db.Preload("InvoiceItem").
        Order(dbOrder).
        Limit(limit).
        Offset(offset).
        Find(&invoices).Error; err != nil {
        return nil, 0, err
    }

    for i := range invoices {
        var sum int64
        for _, item := range invoices[i].InvoiceItem {
            sum += item.PriceCents * item.Quantity
        }
        invoices[i].PriceCents = sum
    }

    return invoices, total, nil
}

