<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;

final class GscDailyPropertyAggRepository
{
    public function __construct(
        private PDO $pdo,
        private string $tablePrefix
    ) {}

    private function table(): string
    {
        return '`' . str_replace('`', '``', $this->tablePrefix . 'gsc_daily_property_agg') . '`';
    }

    public function upsertOne(
        int $propertyId,
        string $siteUrl,
        string $date,
        int $clicks,
        int $impressions,
        float $ctr,
        float $position
    ): void {
        $t = $this->table();
        $now = date('Y-m-d H:i:s');
        $stmt = $this->pdo->prepare(
            "INSERT INTO {$t} (property_id, site_url, date, clicks, impressions, ctr, position, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE clicks = VALUES(clicks),
                                     impressions = VALUES(impressions),
                                     ctr = VALUES(ctr),
                                     position = VALUES(position),
                                     updated_at = VALUES(updated_at)"
        );
        $stmt->execute([
            $propertyId,
            $siteUrl,
            $date,
            $clicks,
            $impressions,
            $ctr,
            $position,
            $now,
        ]);
    }
}

