import pytest
from datetime import datetime
from arepo.models.common.vulnerability import VulnerabilityModel
from arepo.models.source import SourceModel


# Mocked vulnerability data
vulnerability_data = {
    "cve": {
        "id": "CVE-2022-25854",
        "sourceIdentifier": "report@snyk.io",
        "published": "2022-04-29T20:15:07.580",
        "lastModified": "2022-09-23T18:57:11.480",
        "vulnStatus": "Analyzed",
        "descriptions": [
            {
                "lang": "en",
                "value": "This affects the package @yaireo/tagify before 4.9.8. The package is used for rendering UI "
                         "components inside the input or text fields, and an attacker can pass a malicious placeholder "
                         "value to it to fire the XSS payload."
            }
        ]
    }
}


@pytest.mark.dependency(depends=["test_insert_sources"])
@pytest.mark.dependency(name="test_insert_vulnerability")
def test_insert_vulnerability(database_session):
    from sqlalchemy.exc import IntegrityError
    email = vulnerability_data["cve"]["sourceIdentifier"]
    source_id = database_session.query(SourceModel).filter_by(email=email).first().id

    try:
        # Creating VulnerabilityModel object
        vulnerability = VulnerabilityModel(
            id=vulnerability_data["cve"]["id"],
            description=vulnerability_data["cve"]["descriptions"][0]["value"],
            source_id=source_id,
            published_date=datetime.fromisoformat(vulnerability_data["cve"]["published"]),
            last_modified_date=datetime.fromisoformat(vulnerability_data["cve"]["lastModified"])
        )

        database_session.add(vulnerability)
        database_session.commit()
    except IntegrityError:
        database_session.rollback()
        pytest.fail("IntegrityError occurred while inserting vulnerability")


@pytest.mark.dependency(depends=["test_insert_vulnerability"])
def test_get_inserted_vulnerability(database_session):
    # Query the database to retrieve the inserted vulnerability
    retrieved_vulnerability = database_session.query(VulnerabilityModel).filter_by(id="CVE-2022-25854").first()

    # Check if the retrieved vulnerability exists
    assert retrieved_vulnerability is not None
    # Assert the retrieved data matches the expected values
    assert retrieved_vulnerability.id == vulnerability_data["cve"]["id"]
    assert retrieved_vulnerability.description == vulnerability_data["cve"]["descriptions"][0]["value"]
    assert retrieved_vulnerability.source.email == vulnerability_data["cve"]["sourceIdentifier"]


@pytest.mark.dependency(depends=["test_insert_vulnerability"])
def test_get_all_ids_mixin(database_session):
    # Retrieve all vulnerability IDs from the database
    vulnerability_ids = VulnerabilityModel.get_all_ids(database_session)

    # Check if the inserted vulnerability ID is in the retrieved IDs
    assert "CVE-2022-25854" in vulnerability_ids
