<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;

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

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

    /**
     * @param list<array{device: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, device, 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) {
            $dev = strtolower(trim((string) ($r['device'] ?? '')));
            if ($dev === '' || $dev === 'all') {
                continue;
            }
            $stmt->execute([
                $propertyId,
                $siteUrl,
                $date,
                $dev,
                (int) ($r['clicks'] ?? 0),
                (int) ($r['impressions'] ?? 0),
                (float) ($r['ctr'] ?? 0),
                (float) ($r['position'] ?? 0),
                $now,
            ]);
            $count++;
        }
        return $count;
    }
}

