<?php

namespace Myvetshop\Module\Clinique\Adapter\Repository;

use Myvetshop\Module\Clinique\Entity\MyvetshopClinique;

class CombinationRepository
{
    private \Db $db;

    public function __construct(\Db $db)
    {
        $this->db = $db;
    }

    /**
     * Trouves toutes les Combination en Stock pour la clinique donnée et le produit donné
     *
     * @param \Product $product
     *
     * @return array<\Combination>
     */
    public function findByProductInStock(\Product $product, MyvetshopClinique $clinique): array
    {
        $query = 'SELECT pa.*'
            . ' FROM ' . _DB_PREFIX_ . 'product_attribute pa'
            . ' INNER JOIN ' . _DB_PREFIX_ . 'stock s ON s.id_product_attribute = pa.id_product_attribute'
            . ' WHERE pa.id_product = ' . (int) $product->id . ' AND s.id_warehouse = ' . ($clinique->idWarehouse ?? 0)
            . ' AND s.usable_quantity > 0';

        $rows = $this->db->executeS($query);

        if (!\is_array($rows)) {
            $rows = [];
        }

        return \ObjectModel::hydrateCollection(\Combination::class, $rows);
    }
}
