<?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_items table.
 *
 * Part of Issue #165 (Inventory Tracking).
 *
 * @extends QBMapper<StockItem>
 */
class StockItemMapper extends QBMapper {

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

    /**
     * @throws DoesNotExistException
     * @throws Exception
     */
    public function findById(int $id): StockItem {
        $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 stock items.
     *
     * @return StockItem[]
     * @throws Exception
     */
    public function findAll(): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->orderBy('name', 'ASC');

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