from unittest.mock import MagicMock, patch

from prowler.providers.gcp.models import GCPOrganization, GCPProject
from tests.providers.gcp.gcp_fixtures import (
    GCP_EU1_LOCATION,
    GCP_PROJECT_ID,
    set_mocked_gcp_provider,
)


class Test_logging_sink_created:
    def test_no_projects(self):
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = []
            logging_client.sinks = []

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 0

    def test_no_sinks(self):
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = []
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "FAIL"
            assert (
                result[0].status_extended
                == f"There are no logging sinks to export copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == GCP_PROJECT_ID
            assert result[0].resource_name == "test"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_sink_all(self):
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_service import Sink
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [
                Sink(
                    name="sink1",
                    destination="destination1",
                    filter="all",
                    project_id=GCP_PROJECT_ID,
                )
            ]

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "PASS"
            assert (
                result[0].status_extended
                == f"Sink sink1 is enabled exporting copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == "sink1"
            assert result[0].resource_name == "sink1"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_sink_not_all(self):
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_service import Sink
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [
                Sink(
                    name="sink1",
                    destination="destination1",
                    filter="not all",
                    project_id=GCP_PROJECT_ID,
                )
            ]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "FAIL"
            assert (
                result[0].status_extended
                == f"There are no logging sinks to export copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == GCP_PROJECT_ID
            assert result[0].resource_name == "test"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_no_sinks_empty_project_name(self):
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = []
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="",
                    labels={},
                    lifecycle_state="ACTIVE",
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "FAIL"
            assert result[0].resource_id == GCP_PROJECT_ID
            assert result[0].resource_name == "GCP Project"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION
            assert (
                result[0].status_extended
                == f"There are no logging sinks to export copies of all the log entries in project {GCP_PROJECT_ID}."
            )

    def test_project_not_in_projects_dict(self):
        """Test that project not in projects dict uses None and fallback name"""
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = []
            # Project is in project_ids but NOT in projects dict
            logging_client.projects = {}

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "FAIL"
            assert result[0].resource_name == "GCP Project"
            assert result[0].resource_id == GCP_PROJECT_ID
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_sink_with_none_name(self):
        """Test that sink with None name uses fallback 'Logging Sink'"""
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            # Create a MagicMock sink object with name=None
            sink = MagicMock()
            sink.name = None
            sink.filter = "all"
            sink.project_id = GCP_PROJECT_ID
            sink.include_children = False

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [sink]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "PASS"
            assert result[0].resource_name == "Logging Sink"
            assert result[0].resource_id == "unknown"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION
            assert "unknown" in result[0].status_extended

    def test_sink_with_missing_name_attribute(self):
        """Test that sink without name attribute uses fallback 'Logging Sink'"""
        logging_client = MagicMock()

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            # Create a MagicMock sink object without name attribute
            sink = MagicMock(spec=["filter", "project_id", "include_children"])
            sink.filter = "all"
            sink.project_id = GCP_PROJECT_ID
            sink.include_children = False

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [sink]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "PASS"
            assert result[0].resource_name == "Logging Sink"
            assert result[0].resource_id == "unknown"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_org_level_sink_with_include_children_passes(self):
        """Projects covered by an org-level sink with includeChildren=True should PASS."""
        logging_client = MagicMock()
        org_id = "111222333"

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_service import Sink
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [
                Sink(
                    name="org-sink",
                    destination="storage.googleapis.com/org-bucket",
                    filter="all",
                    project_id=f"organizations/{org_id}",
                    include_children=True,
                )
            ]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                    organization=GCPOrganization(
                        id=org_id, name=f"organizations/{org_id}"
                    ),
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "PASS"
            assert (
                result[0].status_extended
                == f"Sink org-sink at organization level is exporting copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == "org-sink"
            assert result[0].project_id == GCP_PROJECT_ID
            assert result[0].location == GCP_EU1_LOCATION

    def test_org_level_sink_without_include_children_fails(self):
        """Projects NOT covered by includeChildren should still FAIL if no direct project sink."""
        logging_client = MagicMock()
        org_id = "111222333"

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_service import Sink
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [
                Sink(
                    name="org-sink-no-children",
                    destination="storage.googleapis.com/org-bucket",
                    filter="all",
                    project_id=f"organizations/{org_id}",
                    include_children=False,
                )
            ]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                    organization=GCPOrganization(
                        id=org_id, name=f"organizations/{org_id}"
                    ),
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "FAIL"
            assert (
                result[0].status_extended
                == f"There are no logging sinks to export copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == GCP_PROJECT_ID
            assert result[0].project_id == GCP_PROJECT_ID

    def test_project_sink_takes_precedence_over_org_sink(self):
        """A direct project sink should be reported even when an org-level sink also covers the project."""
        logging_client = MagicMock()
        org_id = "111222333"

        with (
            patch(
                "prowler.providers.common.provider.Provider.get_global_provider",
                return_value=set_mocked_gcp_provider(),
            ),
            patch(
                "prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created.logging_client",
                new=logging_client,
            ),
        ):
            from prowler.providers.gcp.services.logging.logging_service import Sink
            from prowler.providers.gcp.services.logging.logging_sink_created.logging_sink_created import (
                logging_sink_created,
            )

            logging_client.project_ids = [GCP_PROJECT_ID]
            logging_client.region = GCP_EU1_LOCATION
            logging_client.sinks = [
                Sink(
                    name="project-sink",
                    destination="storage.googleapis.com/project-bucket",
                    filter="all",
                    project_id=GCP_PROJECT_ID,
                ),
                Sink(
                    name="org-sink",
                    destination="storage.googleapis.com/org-bucket",
                    filter="all",
                    project_id=f"organizations/{org_id}",
                    include_children=True,
                ),
            ]
            logging_client.projects = {
                GCP_PROJECT_ID: GCPProject(
                    id=GCP_PROJECT_ID,
                    number="123456789012",
                    name="test",
                    labels={},
                    lifecycle_state="ACTIVE",
                    organization=GCPOrganization(
                        id=org_id, name=f"organizations/{org_id}"
                    ),
                )
            }

            check = logging_sink_created()
            result = check.execute()
            assert len(result) == 1
            assert result[0].status == "PASS"
            assert (
                result[0].status_extended
                == f"Sink project-sink is enabled exporting copies of all the log entries in project {GCP_PROJECT_ID}."
            )
            assert result[0].resource_id == "project-sink"
            assert result[0].project_id == GCP_PROJECT_ID
