"""Issue-related operations."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from zenhub_client.exceptions import ZenhubError
from zenhub_client.graphql import GraphQLClient
from zenhub_client.models import IssueInfo
from zenhub_client.queries import ISSUE_BY_INFO, UPDATE_ISSUE
from zenhub_client.utils import get_in


@dataclass(slots=True)
class IssueService:
    """High-level operations on issues."""

    _graphql: GraphQLClient

    def get_issue_by_info(self, *, repository_gh_id: int, issue_number: int) -> IssueInfo:
        variables = {
            "repositoryGhId": int(repository_gh_id),
            "issueNumber": int(issue_number),
        }
        data = self._graphql.execute(ISSUE_BY_INFO.text, variables)
        node = get_in(data, ["issueByInfo"])
        if not isinstance(node, dict):
            raise ZenhubError(f"Unexpected issueByInfo shape: {node!r}")
        return IssueInfo.from_node(node)

    def update_issue(self, *, issue_id: str, title: str | None = None, body: str | None = None) -> None:
        variables: dict[str, Any] = {
            "issueId": str(issue_id),
            "title": title,
            "body": body,
        }
        self._graphql.execute(UPDATE_ISSUE.text, variables)
