<?php

declare(strict_types=1);

namespace App\Service;

use Hyperf\DbConnection\Db;

/**
 * TimescaleDB 连续聚合刷新实现
 *
 * 调用 PG 的 refresh_continuous_aggregate 存储过程，按整日窗口刷新。
 */
class ContinuousAggregateRefresher implements AggregateRefresherInterface
{
    public function refresh(string $view, string $refresh_date): void
    {
        $start = sprintf("'%s 00:00:00+00'::timestamptz", $refresh_date);
        $end   = sprintf("'%s 23:59:59.999999+00'::timestamptz", $refresh_date);

        // view 在 P23.2 中硬编码为 'orders_daily_by_created'，但仍走 PDO quote 防御
        $quoted_view = Db::getPdo()->quote($view);

        Db::statement(sprintf(
            'CALL refresh_continuous_aggregate(%s, %s, %s)',
            $quoted_view,
            $start,
            $end
        ));
    }
}
