from typing import List

from sator_core.models.vulnerability.references import VulnerabilityReferences

from sator_core.ports.driven.persistence.storage import StoragePersistencePort
from sator_core.ports.driven.repositories.vulnerability import VulnerabilityRepositoryPort
from sator_core.ports.driving.resolution.references.vulnerability import VulnerabilityReferencesResolutionPort


class VulnerabilityReferencesResolution(VulnerabilityReferencesResolutionPort):
    def __init__(
            self, vulnerability_repositories: List[VulnerabilityRepositoryPort], storage_port: StoragePersistencePort
    ):
        self.vulnerability_repositories = vulnerability_repositories
        self.storage_port = storage_port

    def search_vulnerability_references(self, vulnerability_id: str) -> VulnerabilityReferences | None:
        vulnerability_references = self.storage_port.load(VulnerabilityReferences, vulnerability_id)

        if vulnerability_references:
            return vulnerability_references

        vulnerability_references = self._get_vulnerability_references(vulnerability_id)

        if vulnerability_references:
            self.storage_port.save(vulnerability_references, vulnerability_id)

        return vulnerability_references

    def _get_vulnerability_references(self, vulnerability_id: str) -> VulnerabilityReferences | None:
        vulnerability_references = None

        # TODO: find a better way to do this
        for port in self.vulnerability_repositories:
            references = port.get_references(vulnerability_id)

            if not vulnerability_references:
                vulnerability_references = references
            else:
                vulnerability_references.extend(references)

        return vulnerability_references
