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 GetLatestContracts(c *gin.Context) {
	// Get limit and offset from query parameter with defaults
	limitStr := c.DefaultQuery("limit", "99999999999999999999999999999999")
	offsetStr := c.DefaultQuery("offset", "0")
	status := c.DefaultQuery("status", models.ContractStatusActive)

	// Convert limit and offset to int
	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		log.Printf("GetLatestContracts 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("GetLatestContracts Error: Invalid offset value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid offset value"})
		return
	}

	// Create a slice to hold the contracts
	var contracts []models.Contract

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

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

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