<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Db;

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

/**
 * @extends QBMapper<AuditLog>
 */
class AuditLogMapper extends QBMapper {

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

    /**
     * Query audit log entries with optional filters.
     *
     * @return AuditLog[]
     * @throws Exception
     */
    public function findFiltered(
        ?string $entitaet = null,
        ?int $entitaetId = null,
        ?string $ncUserId = null,
        ?string $fromDate = null,
        ?string $toDate = null,
        ?int $limit = null,
        ?int $offset = null
    ): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')->from($this->getTableName());

        if ($entitaet !== null) {
            $qb->andWhere($qb->expr()->eq('entitaet', $qb->createNamedParameter($entitaet)));
        }
        if ($entitaetId !== null) {
            $qb->andWhere($qb->expr()->eq('entitaet_id', $qb->createNamedParameter($entitaetId, IQueryBuilder::PARAM_INT)));
        }
        if ($ncUserId !== null) {
            $qb->andWhere($qb->expr()->eq('nc_user_id', $qb->createNamedParameter($ncUserId)));
        }
        if ($fromDate !== null) {
            $qb->andWhere($qb->expr()->gte('zeitpunkt', $qb->createNamedParameter($fromDate)));
        }
        if ($toDate !== null) {
            $qb->andWhere($qb->expr()->lte('zeitpunkt', $qb->createNamedParameter($toDate)));
        }

        $qb->orderBy('zeitpunkt', 'DESC');

        if ($limit !== null) {
            $qb->setMaxResults($limit);
        }
        if ($offset !== null) {
            $qb->setFirstResult($offset);
        }

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

    /**
     * Count filtered entries.
     *
     * @throws Exception
     */
    public function countFiltered(
        ?string $entitaet = null,
        ?int $entitaetId = null,
        ?string $ncUserId = null
    ): int {
        $qb = $this->db->getQueryBuilder();
        $qb->select($qb->createFunction('COUNT(*)'))
            ->from($this->getTableName());

        if ($entitaet !== null) {
            $qb->andWhere($qb->expr()->eq('entitaet', $qb->createNamedParameter($entitaet)));
        }
        if ($entitaetId !== null) {
            $qb->andWhere($qb->expr()->eq('entitaet_id', $qb->createNamedParameter($entitaetId, IQueryBuilder::PARAM_INT)));
        }
        if ($ncUserId !== null) {
            $qb->andWhere($qb->expr()->eq('nc_user_id', $qb->createNamedParameter($ncUserId)));
        }

        $result = $qb->executeQuery();
        $count = (int)$result->fetchOne();
        $result->closeCursor();
        return $count;
    }
}
