"""Tests for filter module."""

import json
from pathlib import Path

import pytest

from cve_extractor.core import load_cves_from_directory


@pytest.fixture
def sample_cve_directory(tmp_path: Path) -> Path:
    """Create temporary directory with sample CVE JSON files."""
    cve_dir = tmp_path / "cves"
    cve_dir.mkdir()

    # Valid CVE 1
    cve1 = {
        "cveMetadata": {"cveId": "CVE-2024-1234", "datePublished": "2024-01-15"},
        "containers": {
            "cna": {
                "problemTypes": [{"descriptions": [{"cweId": "CWE-79"}]}],
                "descriptions": [{"value": "XSS vulnerability"}],
                "affected": [{"product": "Product A"}],
                "references": [],
            }
        },
    }
    with open(cve_dir / "CVE-2024-1234.json", "w", encoding="utf-8") as f:
        json.dump(cve1, f)

    # Valid CVE 2
    cve2 = {
        "cveMetadata": {"cveId": "CVE-2024-5678", "datePublished": "2024-02-01"},
        "containers": {
            "cna": {
                "problemTypes": [{"descriptions": [{"cweId": "CWE-89"}]}],
                "descriptions": [{"value": "SQL injection"}],
                "affected": [{"product": "Product B"}],
                "references": [],
            }
        },
    }
    with open(cve_dir / "CVE-2024-5678.json", "w", encoding="utf-8") as f:
        json.dump(cve2, f)

    # Malformed CVE (invalid JSON)
    with open(cve_dir / "CVE-2024-9999.json", "w", encoding="utf-8") as f:
        f.write("{invalid json content")

    return cve_dir


def test_load_cves_from_directory(sample_cve_directory: Path) -> None:
    """Test loading CVEs from directory."""
    cves = load_cves_from_directory(sample_cve_directory)

    # Should load 2 valid CVEs, skip 1 malformed
    assert len(cves) == 2

    cve_ids = {cve.cve_id for cve in cves}
    assert "CVE-2024-1234" in cve_ids
    assert "CVE-2024-5678" in cve_ids


def test_load_cves_from_empty_directory(tmp_path: Path) -> None:
    """Test loading from empty directory."""
    empty_dir = tmp_path / "empty"
    empty_dir.mkdir()

    cves = load_cves_from_directory(empty_dir)
    assert len(cves) == 0


def test_load_cves_from_nonexistent_directory(tmp_path: Path) -> None:
    """Test loading from non-existent directory."""
    nonexistent = tmp_path / "nonexistent"

    with pytest.raises(ValueError, match="does not exist"):
        load_cves_from_directory(nonexistent)
