<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Db;

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

/**
 * Mapper for the oc_mv_fee_rules table.
 *
 * Part of Issue #42.
 *
 * @extends QBMapper<FeeRule>
 */
class FeeRuleMapper extends QBMapper {

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

    /**
     * @throws DoesNotExistException
     * @throws MultipleObjectsReturnedException
     * @throws Exception
     */
    public function findById(int $id): FeeRule {
        $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 the applicable fee rule for a given year.
     * Returns the rule with the highest year_from that is <= the given year.
     *
     * @throws DoesNotExistException if no rule applies
     * @throws Exception
     */
    public function findByYear(int $year): FeeRule {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->lte('year_from', $qb->createNamedParameter($year, IQueryBuilder::PARAM_INT)))
            ->orderBy('year_from', 'DESC')
            ->setMaxResults(1);

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

    /**
     * @return FeeRule[]
     * @throws Exception
     */
    public function findAll(): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->orderBy('year_from', 'DESC');

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