package db

import "gorm.io/gorm"

func GetProducts(dbConn *gorm.DB, machineId *int) *[]Product {
	var (
		products []Product
		query    = dbConn
	)

	if machineId != nil {
		query = query.
			Joins("LEFT JOIN machine_products mp ON mp.product_id = products.id").
			Where("mp.machine_id = ?", machineId)
	}

	query.Order("name").Find(&products)

	return &products
}

func GetProduct(dbConn *gorm.DB, id int) (*Product, error) {
	var product Product

	result := dbConn.Order("name").Where("id = ?", id).First(&product)
	if result.Error != nil {
		return nil, result.Error
	}

	return &product, nil
}
