<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;

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

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

    /**
     * @param list<array{page:string,clicks:int,impressions:int,ctr:float,position:float,device?:string,country?:string}> $rows
     */
    public function upsertMany(int $propertyId, string $siteUrl, string $date, array $rows, string $device = 'all', string $country = 'all'): 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, page, device, country, clicks, impressions, ctr, position, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE clicks = VALUES(clicks),
                                     impressions = VALUES(impressions),
                                     ctr = VALUES(ctr),
                                     position = VALUES(position),
                                     device = VALUES(device),
                                     country = VALUES(country),
                                     property_id = VALUES(property_id),
                                     updated_at = VALUES(updated_at)"
        );
        $count = 0;
        foreach ($rows as $r) {
            $p = trim((string) ($r['page'] ?? ''));
            if ($p === '') {
                continue;
            }
            $dev = strtolower(trim((string) ($r['device'] ?? $device)));
            $ctr3 = strtolower(trim((string) ($r['country'] ?? $country)));
            if ($dev === '') $dev = 'all';
            if ($ctr3 === '') $ctr3 = 'all';
            $stmt->execute([
                $propertyId > 0 ? $propertyId : null,
                $siteUrl,
                $date,
                $p,
                $dev,
                $ctr3,
                (int) ($r['clicks'] ?? 0),
                (int) ($r['impressions'] ?? 0),
                (float) ($r['ctr'] ?? 0),
                (float) ($r['position'] ?? 0),
                $now,
            ]);
            $count++;
        }
        return $count;
    }
}

