<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;

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

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

    /**
     * @param list<array{country:string,clicks:int,impressions:int,ctr:float,position:float}> $rows
     */
    public function upsertMany(int $propertyId, string $siteUrl, string $date, array $rows): int
    {
        if ($rows === []) {
            return 0;
        }
        $t = $this->table();
        $now = date('Y-m-d H:i:s');
        $stmt = $this->pdo->prepare(
            "INSERT INTO {$t} (property_id, site_url, date, country, clicks, impressions, ctr, position, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE clicks = VALUES(clicks),
                                     impressions = VALUES(impressions),
                                     ctr = VALUES(ctr),
                                     position = VALUES(position),
                                     site_url = VALUES(site_url),
                                     updated_at = VALUES(updated_at)"
        );
        $count = 0;
        foreach ($rows as $r) {
            $c = strtolower(trim((string) ($r['country'] ?? '')));
            if ($c === '' || $c === 'all') {
                continue;
            }
            $stmt->execute([
                $propertyId,
                $siteUrl,
                $date,
                $c,
                (int) ($r['clicks'] ?? 0),
                (int) ($r['impressions'] ?? 0),
                (float) ($r['ctr'] ?? 0),
                (float) ($r['position'] ?? 0),
                $now,
            ]);
            $count++;
        }
        return $count;
    }
}

