from typing import List

from sator_core.models.vulnerability import VulnerabilityMetadata, VulnerabilityDescription

from sator_core.ports.driven.persistence.storage import StoragePersistencePort
from sator_core.ports.driven.repositories.vulnerability import VulnerabilityRepositoryPort
from sator_core.ports.driving.resolution.metadata.vulnerability import VulnerabilityMetadataResolutionPort


class VulnerabilityMetadataResolution(VulnerabilityMetadataResolutionPort):
    def __init__(self, vuln_repositories: List[VulnerabilityRepositoryPort], storage_port: StoragePersistencePort):
        self.vuln_repositories = vuln_repositories
        self.storage_port = storage_port

    def resolve_vulnerability_metadata(self, vulnerability_id: str) -> VulnerabilityMetadata | None:
        vulnerability = self.storage_port.load(VulnerabilityMetadata, vulnerability_id)

        if vulnerability and isinstance(vulnerability, VulnerabilityMetadata):
            return vulnerability

        #  TODO: should consider all metadata and not just the first one
        for port in self.vuln_repositories:
            vulnerability = port.get_metadata(vulnerability_id)
            self.storage_port.save(vulnerability, vulnerability_id)

            if vulnerability:
                return vulnerability

        return None

    def resolve_vulnerability_description(self, vulnerability_id: str) -> VulnerabilityDescription | None:
        description = self.storage_port.load(VulnerabilityDescription, vulnerability_id)

        if description:
            return description

        #  TODO: should consider all descriptions and not just the first one
        for port in self.vuln_repositories:
            description = port.get_description(vulnerability_id)

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

                return description

        return None
