package company

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

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

func GetCompanies(companyIDs []int64, limit, offset int) ([]models.Company, int64, int, error) {

	companies := []models.Company{}
	db := shared.GetDb()
	countDb := db

	// Search by IDs
	if len(companyIDs) > 0 {
		db = db.Where("companies.id IN (?)", companyIDs)
		countDb = countDb.Where("companies.id IN (?)", companyIDs)
	}

	// Fetch total count of filtered records
	var total int64
	if err := countDb.Model(&models.Company{}).Count(&total).Error; err != nil {
		log.Printf("GetCompanies Error: Database error: %v", err)
		return companies, total, http.StatusInternalServerError, err
	}

	// Fetch companies with custom fields
	if err := db.Select("*").
		Order("created_at desc").
		Limit(limit).
		Offset(offset).
		Find(&companies).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Printf("GetCompanies Error: No companies found: %v", err)
			return companies, total, http.StatusNotFound, err
		} else {
			log.Printf("GetCompanies Error: Database error: %v", err)
			return companies, total, http.StatusInternalServerError, err
		}
	}

	return companies, total, http.StatusOK, nil
}
