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

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

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

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

    /**
     * Find items whose condition falls within the given range.
     *
     * @param int|null $min Minimum condition (inclusive), null = unbounded
     * @param int|null $max Maximum condition (inclusive), null = unbounded
     * @return GeneralMaterial[]
     * @throws Exception
     */
    public function findByConditionRange(?int $min = null, ?int $max = null): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->isNotNull('condition'));

        if ($min !== null) {
            $qb->andWhere($qb->expr()->gte('condition', $qb->createNamedParameter($min, IQueryBuilder::PARAM_INT)));
        }
        if ($max !== null) {
            $qb->andWhere($qb->expr()->lte('condition', $qb->createNamedParameter($max, IQueryBuilder::PARAM_INT)));
        }

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

    /**
     * Find items needing repair (condition ≤ 2 or NULL).
     *
     * @return GeneralMaterial[]
     * @throws Exception
     */
    public function findNeedingRepair(): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->lte('condition', $qb->createNamedParameter(2, IQueryBuilder::PARAM_INT)))
            ->orWhere($qb->expr()->isNull('condition'));

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