<?php
namespace Analytics\Repositories;

use Analytics\Lib\Database;

class QueryDataRepository
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function insertMany(int $snapshotId, int $projectId, array $queries): void
    {
        foreach ($queries as $q) {
            $this->db->insert('analytics_query_data', [
                'snapshot_id' => $snapshotId,
                'project_id'  => $projectId,
                'query'       => $q['query'],
                'clicks'      => (int)($q['clicks']      ?? 0),
                'impressions' => (int)($q['impressions'] ?? 0),
                'ctr'         => (float)($q['ctr']       ?? 0),
                'position'    => (float)($q['position']  ?? 0),
                'created_at'  => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function bySnapshot(int $snapshotId, int $limit = 100, int $offset = 0): array
    {
        return $this->db->fetchAll(
            "SELECT query, clicks, impressions, ctr, position
             FROM analytics_query_data WHERE snapshot_id = ?
             ORDER BY clicks DESC
             LIMIT {$limit} OFFSET {$offset}",
            [$snapshotId]
        );
    }

    public function deleteBySnapshot(int $snapshotId): void
    {
        $this->db->query('DELETE FROM analytics_query_data WHERE snapshot_id = ?', [$snapshotId]);
    }
}
