<?php
namespace Crawl\Repositories;

use Crawl\Lib\Database;

class CrawlRunRepository
{
    private Database $db;

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

    public function create(array $data): int
    {
        return $this->db->insert('crawl_runs', $data);
    }

    public function findById(int $id, int $projectId): ?array
    {
        return $this->db->fetch('SELECT * FROM crawl_runs WHERE id = ? AND project_id = ?', [$id, $projectId]);
    }

    public function latestForProject(int $projectId): ?array
    {
        return $this->db->fetch('SELECT * FROM crawl_runs WHERE project_id = ? ORDER BY id DESC LIMIT 1', [$projectId]);
    }

    public function listByProject(int $projectId, int $limit = 50): array
    {
        return $this->db->fetchAll(
            'SELECT id, domain, status, total_pages, started_at, finished_at
             FROM crawl_runs
             WHERE project_id = ?
             ORDER BY id DESC
             LIMIT ' . (int)$limit,
            [$projectId]
        );
    }

    public function updateStatus(int $runId, string $status, ?string $error = null): bool
    {
        return $this->db->update('crawl_runs', [
            'status' => $status,
            'error_message' => $error,
            'finished_at' => in_array($status, ['completed', 'failed'], true) ? date('Y-m-d H:i:s') : null,
        ], 'id = :id', ['id' => $runId]);
    }

    public function incrementTotalPages(int $runId): void
    {
        $this->db->query('UPDATE crawl_runs SET total_pages = total_pages + 1 WHERE id = ?', [$runId]);
    }

    public function countPendingQueue(int $runId): int
    {
        $row = $this->db->fetch('SELECT COUNT(*) AS cnt FROM crawl_queue WHERE crawl_run_id = ? AND status IN (\'pending\', \'processing\')', [$runId]);
        return (int)($row['cnt'] ?? 0);
    }

    public function countFailedQueue(int $runId): int
    {
        $row = $this->db->fetch('SELECT COUNT(*) AS cnt FROM crawl_queue WHERE crawl_run_id = ? AND status = \'failed\'', [$runId]);
        return (int)($row['cnt'] ?? 0);
    }

    public function allRunning(): array
    {
        return $this->db->fetchAll('SELECT * FROM crawl_runs WHERE status = \'running\' ORDER BY id ASC');
    }

    public function syncTotalPagesFromRows(int $runId): void
    {
        $this->db->query('UPDATE crawl_runs SET total_pages = (SELECT COUNT(*) FROM crawl_pages WHERE crawl_run_id = ?) WHERE id = ?', [$runId, $runId]);
    }
}
