"""Activities for Teams service via GraphQL M2M endpoint."""

import logging

import httpx
from temporalio import activity

from optovia_workflows.types import (
    CreateTeamInput,
    CreateTeamResult,
    SetLogtoOrgIdInput,
    SetLogtoOrgIdResult,
)

from ..config import settings

logger = logging.getLogger(__name__)


CREATE_TEAM_MUTATION = """
mutation CreateTeamFromWorkflow($teamName: String!, $ownerId: String!, $teamType: String, $countryCode: String) {
    createTeamFromWorkflow(teamName: $teamName, ownerId: $ownerId, teamType: $teamType, countryCode: $countryCode) {
        success
        teamId
        teamUuid
        message
    }
}
"""

SET_LOGTO_ORG_ID_MUTATION = """
mutation SetLogtoOrgId($teamId: String!, $logtoOrgId: String!) {
    setLogtoOrgId(teamId: $teamId, logtoOrgId: $logtoOrgId) {
        success
        team {
            id
            logtoOrgId
        }
    }
}
"""


@activity.defn(name="create_team_in_teams")
def create_team_in_teams(data: CreateTeamInput) -> CreateTeamResult:
    """
    Create Team in Teams service via GraphQL M2M endpoint.

    This is a synchronous activity (runs in ThreadPoolExecutor).
    Called from KYC workflow after approval.
    """
    url = f"http://{settings.TEAMS_INTERNAL_URL}/graphql/m2m/"

    logger.info(
        "Creating team '%s' for owner %s (type=%s)",
        data.team_name,
        data.owner_id,
        data.team_type,
    )

    with httpx.Client(timeout=settings.TEAMS_TIMEOUT) as client:
        response = client.post(
            url,
            json={
                "query": CREATE_TEAM_MUTATION,
                "variables": {
                    "teamName": data.team_name,
                    "ownerId": data.owner_id,
                    "teamType": data.team_type,
                    "countryCode": data.country_code,
                },
            },
            headers={"Content-Type": "application/json"},
        )
        response.raise_for_status()

        result = response.json()
        if "errors" in result:
            raise Exception(f"GraphQL errors: {result['errors']}")

        mutation_result = result.get("data", {}).get("createTeamFromWorkflow", {})
        if not mutation_result.get("success"):
            raise Exception(f"Failed to create team: {mutation_result.get('message')}")

    team_id = mutation_result.get("teamId", "")
    team_uuid = mutation_result.get("teamUuid", "")

    logger.info("Team created: id=%s uuid=%s", team_id, team_uuid)

    return CreateTeamResult(
        success=True,
        team_id=team_id,
        team_uuid=team_uuid,
        message="Team created",
    )


@activity.defn(name="set_logto_org_id")
def set_logto_org_id(data: SetLogtoOrgIdInput) -> SetLogtoOrgIdResult:
    """
    Set Logto organization ID in Teams service via GraphQL M2M endpoint.

    This is a synchronous activity (runs in ThreadPoolExecutor).
    """
    url = f"http://{settings.TEAMS_INTERNAL_URL}/graphql/m2m/"

    logger.info(
        "Setting logto_org_id for team %s to %s",
        data.team_id,
        data.logto_org_id,
    )

    with httpx.Client(timeout=settings.TEAMS_TIMEOUT) as client:
        response = client.post(
            url,
            json={
                "query": SET_LOGTO_ORG_ID_MUTATION,
                "variables": {
                    "teamId": data.team_id,
                    "logtoOrgId": data.logto_org_id,
                },
            },
            headers={"Content-Type": "application/json"},
        )
        response.raise_for_status()

        result = response.json()
        if "errors" in result:
            raise Exception(f"GraphQL errors: {result['errors']}")

        mutation_result = result.get("data", {}).get("setLogtoOrgId", {})
        if not mutation_result.get("success"):
            raise Exception("Failed to set logto org id")

    logger.info("Team %s logto_org_id set to %s", data.team_id, data.logto_org_id)

    return SetLogtoOrgIdResult(
        team_id=data.team_id,
        logto_org_id=data.logto_org_id,
        updated=True,
    )
