"""Tests for extractor module."""

import csv
from pathlib import Path

import pytest

from cve_extractor.core import extract_cves_to_csv
from cve_extractor.core import CVERecord


@pytest.fixture
def sample_cves() -> list[CVERecord]:
    """Sample CVE records."""
    return [
        CVERecord(
            cve_id="CVE-2024-1234",
            cwe_types=["CWE-79"],
            description="XSS vulnerability in web application",
            affected_products=["Product A"],
            references=["https://example.com"],
            published_date="2024-01-15",
        ),
        CVERecord(
            cve_id="CVE-2024-5678",
            cwe_types=["CWE-89", "CWE-20"],
            description="SQL injection vulnerability",
            affected_products=["Product B"],
            references=["https://example.com"],
            published_date="2024-02-01",
        ),
    ]


def test_extract_cves_to_csv(sample_cves: list[CVERecord], tmp_path: Path) -> None:
    """Test extracting CVEs to CSV."""
    output_file = tmp_path / "output.csv"

    extract_cves_to_csv(sample_cves, output_file)

    assert output_file.exists()

    # Read and verify CSV
    with open(output_file, encoding="utf-8") as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    assert len(rows) == 2

    # Verify first row
    assert rows[0]["CVE ID"] == "CVE-2024-1234"
    assert rows[0]["CWE Type"] == "CWE-79"
    assert "XSS" in rows[0]["Description"]

    # Verify second row
    assert rows[1]["CVE ID"] == "CVE-2024-5678"
    assert rows[1]["CWE Type"] == "CWE-89"  # First CWE type
    assert "SQL" in rows[1]["Description"]


def test_extract_cves_empty_list(tmp_path: Path) -> None:
    """Test extracting empty CVE list."""
    output_file = tmp_path / "output.csv"

    with pytest.raises(ValueError, match="cannot be empty"):
        extract_cves_to_csv([], output_file)


def test_extract_cves_long_description(tmp_path: Path) -> None:
    """Test truncation of long descriptions."""
    long_desc = "A" * 300  # 300 characters

    cves = [
        CVERecord(
            cve_id="CVE-2024-1234",
            cwe_types=["CWE-79"],
            description=long_desc,
            affected_products=[],
            references=[],
            published_date="2024-01-15",
        )
    ]

    output_file = tmp_path / "output.csv"
    extract_cves_to_csv(cves, output_file)

    # Read and verify truncation
    with open(output_file, encoding="utf-8") as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    assert len(rows[0]["Description"]) == 200
    assert rows[0]["Description"].endswith("...")
