<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Db;

use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;

/**
 * Mapper for the oc_mv_inventory_stock_variants table.
 *
 * Part of Issue #165 (Inventory Tracking).
 *
 * @extends QBMapper<StockVariant>
 */
class StockVariantMapper extends QBMapper {

    public function __construct(IDBConnection $db) {
        parent::__construct($db, 'mv_inventory_stock_variants', StockVariant::class);
    }

    /**
     * @throws DoesNotExistException
     * @throws Exception
     */
    public function findById(int $id): StockVariant {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT)));

        return $this->findEntity($qb);
    }

    /**
     * Find all variants for a given stock item.
     *
     * @return StockVariant[]
     * @throws Exception
     */
    public function findByStockItemId(int $stockItemId): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->eq('stock_item_id', $qb->createNamedParameter($stockItemId, IQueryBuilder::PARAM_INT)))
            ->orderBy('label', 'ASC');

        return $this->findEntities($qb);
    }
}
