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

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

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

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

    /**
     * Find sale records within a date range.
     *
     * @param string|null $from Start date (inclusive, YYYY-MM-DD)
     * @param string|null $to   End date (inclusive, YYYY-MM-DD)
     * @return SaleRecord[]
     * @throws Exception
     */
    public function findByDateRange(?string $from = null, ?string $to = null): array {
        $qb = $this->db->getQueryBuilder();
        $qb->select('*')
            ->from($this->getTableName())
            ->where($qb->expr()->gte('date', $qb->createNamedParameter($from ?? '1970-01-01', IQueryBuilder::PARAM_STR)))
            ->addOrderBy('date', 'DESC');

        if ($to !== null) {
            // Override the first where (set up by gte)
            $conditions = $qb->expr()->gte('date', $qb->createNamedParameter($from ?? '1970-01-01', IQueryBuilder::PARAM_STR));
            $conditions2 = $qb->expr()->lte('date', $qb->createNamedParameter($to, IQueryBuilder::PARAM_STR));
            $qb2 = $this->db->getQueryBuilder();
            $qb2->select('*')
                ->from($this->getTableName())
                ->where($conditions2)
                ->andWhere($conditions);

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

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

    /**
     * Count sale records within a date range.
     *
     * @throws Exception
     */
    public function countByDateRange(?string $from = null, ?string $to = null): int {
        $qb = $this->db->getQueryBuilder();
        $qb->select($qb->createFunction('COUNT(*)'))
            ->from($this->getTableName())
            ->where($qb->expr()->gte('date', $qb->createNamedParameter($from ?? '1970-01-01', IQueryBuilder::PARAM_STR)));

        if ($to !== null) {
            $qb->andWhere($qb->expr()->lte('date', $qb->createNamedParameter($to, IQueryBuilder::PARAM_STR)));
        }

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

        return $count;
    }
}
