<?php

namespace Shopping\Sphinx;

use Generator;
use PDO;

class SphinxSource {
    private PDO $pdo;

    private const BATCH_SIZE = 50000;      // must be <= max_matches
    private const MAX_MATCHES = 55000;  // safe upper bound

    public function __construct(SphinxConnection $connection) {
        $this->pdo = $connection->getPdo();
    }

    public function fetch(
        string  $index,
        ?string $feed = null
    ): Generator {

        $lastId = 0;

        while (true) {
            $where = ['id > ' . (int)$lastId];

            if ($feed !== null) {
                $where[] = "feed_name = '" . addslashes($feed) . "'";
            }

            $sql = "
                SELECT *
                FROM {$index}
                WHERE " . implode(' AND ', $where) . "
                ORDER BY id ASC
                LIMIT " . self::BATCH_SIZE . "
                OPTION max_matches = " . self::MAX_MATCHES;

            $stmt = $this->pdo->query($sql);

            $rowsFetched = 0;

            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $rowsFetched++;
                $lastId = (int)$row['id'];
                yield new SphinxRow($row);
            }

            if ($rowsFetched < self::BATCH_SIZE) {
                break;
            }
            error_log(date('Y-m-d H:i:s') . "[FEED] Writing {$lastId} written rows={$rowsFetched}");
        }
    }
}