import unittest
from typing import Any

from src.aiel_sdk.services.integrations import IntegrationsService


class _FakeAielClient:
    def __init__(self, result: Any = None):
        self.result = result
        self.calls = []

    def _request(self, service: str, method: str, path: str, *, params=None, json_body=None, request_id=None):
        self.calls.append(
            {
                "service": service,
                "method": method,
                "path": path,
                "params": params,
                "json_body": json_body,
                "request_id": request_id,
            }
        )
        return self.result


class IntegrationsServiceTests(unittest.TestCase):
    def test_list_calls_client_with_service_and_parses_models(self):
        fake = _FakeAielClient(
            result=[
                {
                    "connection_id": "c1",
                    "workspace_id": "w1",
                    "project_id": "p1",
                    "provider": "jira",
                    "connector": {"id": "jira", "version": "1.0.0"},
                    "resource_type": "jira.site",
                    "display_name": "Jira Connection",
                    "status": "connected",
                    "status_reason": None,
                    "capabilities": [],
                    "allowed_actions": [],
                    "granted_actions": [],
                    "auth": {"method": "oauth"},
                    "metadata": {},
                }
            ]
        )
        svc = IntegrationsService(fake)

        items = svc.list("w1", "p1")
        self.assertEqual(len(items), 1)
        self.assertEqual(items[0].connection_id, "c1")
        self.assertEqual(fake.calls[-1]["service"], "integrations")
        self.assertEqual(fake.calls[-1]["method"], "GET")
        self.assertEqual(fake.calls[-1]["path"], "/v1/workspaces/w1/projects/p1/integrations")

    def test_invoke_action_forwards_request_id(self):
        fake = _FakeAielClient(result={"ok": True})
        svc = IntegrationsService(fake)

        out = svc.invoke_action(
            "w1",
            "p1",
            "c1",
            "slack.post_message",
            {"params": {"channel": "C1"}},
            request_id="req_123",
        )

        self.assertEqual(out.get("ok"), True)
        call = fake.calls[-1]
        self.assertEqual(call["service"], "integrations")
        self.assertEqual(call["method"], "POST")
        self.assertEqual(
            call["path"],
            "/v1/workspaces/w1/projects/p1/integrations/c1/action/slack.post_message:invoke",
        )
        self.assertEqual(call["json_body"], {"params": {"channel": "C1"}})
        self.assertEqual(call["request_id"], "req_123")


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