package controllers

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

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

func ListCompanies(c *gin.Context) {
	// Get limit and offset from query parameter with defaults
	limitStr := c.DefaultQuery("limit", "50")
	offsetStr := c.DefaultQuery("offset", "0")
	iDsStr := c.QueryArray("ids[]")

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

	// Convert ids to []int64
	var companyIDs []int64
	for _, idStr := range iDsStr {
		id, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid id value"})
			return
		}
		companyIDs = append(companyIDs, id)
	}

	// Fetch companies
	companies, total, st, err := company.GetCompanies(companyIDs, limit, offset)
	if err != nil {
		c.JSON(st, gin.H{"error": err.Error()})
		return
	}

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

func GetCompanyByID(c *gin.Context) {
	// Get the company ID from url parameters
	companyIDStr := c.Param("company_id")

	if companyIDStr == "" {
		log.Printf("GetCompanyByID Error: ID is required")
		c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
		return
	}

	companyID, err := strconv.ParseUint(companyIDStr, 10, 32)
	if err != nil {
		log.Printf("GetCompanyByID Error: Invalid ID: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
		return
	}

	// Fetch company
	companies, _, st, err := company.GetCompanies([]int64{int64(companyID)}, 1, 0)
	if err != nil {
		c.JSON(st, gin.H{"error": err.Error()})
		return
	}

	// Respond with the companies and the total count
	c.JSON(http.StatusOK, gin.H{"data": companies[0]})
}
