<?php
namespace Crawl\Repositories;

use Crawl\Lib\Database;

class PageSpeedRepository
{
    private Database $db;

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

    public function upsert(int $runId, int $projectId, string $url, string $strategy, array $data): void
    {
        $this->db->query(
            'DELETE FROM crawl_pagespeed WHERE crawl_run_id = ? AND url = ? AND strategy = ?',
            [$runId, $url, $strategy]
        );
        $this->db->insert('crawl_pagespeed', [
            'crawl_run_id'  => $runId,
            'project_id'    => $projectId,
            'url'           => $url,
            'strategy'      => $strategy,
            'score'         => $data['score']         ?? null,
            'fcp'           => $data['fcp']           ?? null,
            'lcp'           => $data['lcp']           ?? null,
            'tbt'           => $data['tbt']           ?? null,
            'cls'           => $data['cls']           ?? null,
            'si'            => $data['si']            ?? null,
            'tti'           => $data['tti']           ?? null,
            'score_seo'     => $data['score_seo']     ?? null,
            'score_a11y'    => $data['score_a11y']    ?? null,
            'score_bp'      => $data['score_bp']      ?? null,
            'opportunities' => isset($data['opportunities']) ? json_encode($data['opportunities']) : null,
            'fetched_at'    => date('Y-m-d H:i:s'),
        ]);
    }

    public function forRun(int $runId, int $projectId): array
    {
        $rows = $this->db->fetchAll(
            'SELECT * FROM crawl_pagespeed WHERE crawl_run_id = ? AND project_id = ? ORDER BY strategy ASC',
            [$runId, $projectId]
        );
        $out = [];
        foreach ($rows as $row) {
            if (!empty($row['opportunities']) && is_string($row['opportunities'])) {
                $row['opportunities'] = json_decode($row['opportunities'], true) ?? [];
            }
            $out[$row['strategy']] = $row;
        }
        return $out;
    }

    public function hasData(int $runId, int $projectId): bool
    {
        $row = $this->db->fetch(
            'SELECT id FROM crawl_pagespeed WHERE crawl_run_id = ? AND project_id = ? LIMIT 1',
            [$runId, $projectId]
        );
        return (bool)$row;
    }
}
