package contract

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

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

func GetContracts(status string, companyName string, companyAddress string, 
	companyEmail string, companyPhone string, startTime time.Time, endTime time.Time,
	 contractName string, deviceIDs []int64, limit, offset int) ([]models.Contract, int64, int, error) {
    var contracts []models.Contract
    db := shared.GetDb()

    countDb := db

    // Search by Status
    if status != "" {
		db = shared.GetDb().Where("contracts.status = ?", status)
        countDb = countDb.Where("contracts.status = ?", status)
    }

    // Search by Company Fields
    if companyName != "" || companyAddress != "" || companyEmail != "" || companyPhone != "" {
        db = db.Joins("left join companies on companies.id = contracts.buyer_id")
        countDb = countDb.Joins("left join companies on companies.id = contracts.buyer_id")

        if companyName != "" {
            db = db.Where("companies.name LIKE ?", "%"+companyName+"%")
            countDb = countDb.Where("companies.name LIKE ?", "%"+companyName+"%")
        }

        if companyAddress != "" {
            db = db.Where("companies.address LIKE ?", "%"+companyAddress+"%")
            countDb = countDb.Where("companies.address LIKE ?", "%"+companyAddress+"%")
        }

        if companyEmail != "" {
            db = db.Where("companies.email LIKE ?", "%"+companyEmail+"%")
            countDb = countDb.Where("companies.email LIKE ?", "%"+companyEmail+"%")
        }

        if companyPhone != "" {
            db = db.Where("companies.phone LIKE ?", "%"+companyPhone+"%")
            countDb = countDb.Where("companies.phone LIKE ?", "%"+companyPhone+"%")
        }
    }

    // Search by Contract Name
	if contractName != "" {
		db = db.Where("contracts.name LIKE ?", "%"+contractName+"%")
		countDb = countDb.Where("contracts.name LIKE ?", "%"+contractName+"%")
	}

    // Search by Start Time
    if !startTime.IsZero() {
        db = db.Where("start_time >= ?", startTime)
        countDb = countDb.Where("start_time >= ?", startTime)
    }

    // Search by End Time
    if !endTime.IsZero() {
        db = db.Where("end_time <= ?", endTime)
        countDb = countDb.Where("end_time <= ?", endTime)
    }

    // Search by Device IDs
    if len(deviceIDs) > 0 {
		db = db.Where("device_ids && ?", pq.Array(deviceIDs))
		countDb = countDb.Where("device_ids && ?", pq.Array(deviceIDs))
    }

    var total int64
    if err := countDb.Model(&models.Contract{}).Count(&total).Error; err != nil {
        log.Printf("GetContracts Error: Database error: %v", err)
        return contracts, total, http.StatusInternalServerError, err
    }

    if err := db.Order("created_at desc").Limit(limit).Offset(offset).Find(&contracts).Error; err != nil {
        if errors.Is(err, gorm.ErrRecordNotFound) {
            log.Printf("GetContracts Error: No contracts found: %v", err)
            return contracts, total, http.StatusNotFound, err
        } else {
            log.Printf("GetContracts Error: Database error: %v", err)
            return contracts, total, http.StatusInternalServerError, err
        }
    }

    return contracts, total, http.StatusOK, nil
}




func GetContractByID(contractID uint64) (models.Contract, int ,error) {

	// Fetch the contract creation date based on contractID
	var contract models.Contract
	if err := shared.GetDb().Where("id = ?", contractID).First(&contract).Error; err != nil {
		log.Printf("GetDeviceData Error: Could not fetch contract: %v", err)
		return contract, http.StatusInternalServerError, err
	}
	
	return  contract ,  http.StatusOK, nil

}