# tests/test_applications.py
import unittest

from anypoint_sdk._http import HttpClient
from anypoint_sdk.resources.applications import Applications
from tests.fakes import FakeSession
from tests.helpers import make_response

BASE = "https://api.test.local"


class ApplicationsTests(unittest.TestCase):
    def test_list_normalises_captures_credentials_and_dedupes(self):
        org_id = "o1"
        payload = {
            "applications": [
                {
                    "audit": {
                        "created": {"date": "2025-08-15T09:34:36.561Z"},
                        "updated": {},
                    },
                    "id": 2693831,
                    "name": "treasury-app-1",
                    "description": None,
                    "coreServicesId": "f3f1e789327f4d41b3bcbc9890764ae4",
                    "url": None,
                    "clientId": "f3f1e789327f4d41b3bcbc9890764ae4",
                    "clientSecret": "c58c08f1702E49dAb27771887D93A4A5",
                    "grantTypes": [],
                    "redirectUri": [],
                    "owner": "Mule User",
                    "email": "mule-user-1@proton.me",
                    "owners": [
                        {
                            "id": "2a0...",
                            "organizationId": "o1",
                            "firstName": "Mule",
                            "lastName": "User",
                            "email": "mule-user-1@proton.me",
                            "username": "mule-user-1",
                            "entityType": "user",
                        },
                        "bad",  # ignored
                    ],
                },
                # duplicate id to prove dedupe
                {"id": 2693831, "name": "dupe"},
            ],
            "total": 2,
        }
        resp = make_response(
            status=200,
            json_body=payload,
            url=f"{BASE}/apiplatform/repository/v2/organizations/{org_id}/applications",
        )
        fake = FakeSession([resp])
        http = HttpClient(base_url=BASE, session=fake, retries=0)

        out = Applications(http).list(org_id)

        self.assertEqual(len(out), 1)
        app = out[0]
        self.assertEqual(app["id"], 2693831)
        self.assertEqual(app["name"], "treasury-app-1")
        self.assertEqual(app["clientId"], "f3f1e789327f4d41b3bcbc9890764ae4")
        self.assertEqual(app["clientSecret"], "c58c08f1702E49dAb27771887D93A4A5")
        self.assertEqual(app["ownerName"], "Mule User")
        self.assertEqual(app["ownerEmail"], "mule-user-1@proton.me")
        self.assertIsInstance(app["owners"], list)
        # Confirm the query param was set
        self.assertEqual(fake.calls[0]["params"]["targetAdminSite"], "true")

    def test_list_handles_missing_or_wrong_shape(self):
        org_id = "o1"
        # No 'applications' key
        resp1 = make_response(
            status=200,
            json_body={"total": 0},
            url=f"{BASE}/apiplatform/repository/v2/organizations/{org_id}/applications",
        )
        http1 = HttpClient(base_url=BASE, session=FakeSession([resp1]), retries=0)
        out1 = Applications(http1).list(org_id)
        self.assertEqual(out1, [])

        # 'applications' is wrong type
        resp2 = make_response(
            status=200,
            json_body={"applications": {"unexpected": True}},
            url=f"{BASE}/apiplatform/repository/v2/organizations/{org_id}/applications",
        )
        http2 = HttpClient(base_url=BASE, session=FakeSession([resp2]), retries=0)
        out2 = Applications(http2).list(org_id)
        self.assertEqual(out2, [])

    def test_list_ignores_non_dict_and_normalises_lists(self):
        org_id = "o1"
        payload = {
            "applications": [
                "bad",
                123,
                {
                    "id": 1,
                    "name": "app-1",
                    "grantTypes": ["client_credentials", 7, None],
                    "redirectUri": ["https://a.example/cb", {"oops": True}],
                },
            ]
        }
        resp = make_response(
            status=200,
            json_body=payload,
            url=f"{BASE}/apiplatform/repository/v2/organizations/{org_id}/applications",
        )
        http = HttpClient(base_url=BASE, session=FakeSession([resp]), retries=0)
        out = Applications(http).list(org_id)

        self.assertEqual(len(out), 1)
        self.assertEqual(out[0]["grantTypes"], ["client_credentials"])
        self.assertEqual(out[0]["redirectUri"], ["https://a.example/cb"])

    def test_list_allows_disabling_target_admin_site(self):
        org_id = "o1"
        resp = make_response(
            status=200,
            json_body={"applications": []},
            url=f"{BASE}/apiplatform/repository/v2/organizations/{org_id}/applications",
        )
        fake = FakeSession([resp])
        http = HttpClient(base_url=BASE, session=fake, retries=0)

        Applications(http).list(org_id, target_admin_site=False)

        self.assertEqual(fake.calls[0]["params"]["targetAdminSite"], "false")


if __name__ == "__main__":
    unittest.main()
