# Generated by ariadne-codegen
# Source: hubsrht/services/todo/

from typing import Any, Optional, Union

import httpx
from flask import has_request_context, request
from srht.config import cfg, get_origin
from srht.graphql import InternalAuth

from .base_client import BaseClient
from .base_model import UNSET, UnsetType
from .create_tracker import CreateTracker
from .create_tracker_webhook import CreateTrackerWebhook
from .create_user_webhook import CreateUserWebhook
from .delete_tracker import DeleteTracker
from .delete_tracker_webhook import DeleteTrackerWebhook
from .delete_user_webhook import DeleteUserWebhook
from .enums import Visibility
from .event_webhook import EventWebhook
from .get_ticket_comments import GetTicketComments
from .get_tracker import GetTracker
from .get_trackers import GetTrackers
from .input_types import SubmitCommentInput
from .submit_comment import SubmitComment


def gql(q: str) -> str:
    return q


class TodoClient(BaseClient):
    def __init__(self, auth=None, headers=None, client=None, **kwargs):
        origin = cfg("todo.sr.ht", "api-origin", default=get_origin("todo.sr.ht"))
        if auth is None:
            auth = InternalAuth()
        headers = {**auth.headers, "User-Agent": "todo.sr.ht frontend"}
        if has_request_context():
            headers["X-Forwarded-For"] = ", ".join(request.access_route)
        if not client:
            backend_timeout = cfg("todo.sr.ht", "backend-timeout", default=3)
            client = httpx.Client(
                headers=headers, timeout=httpx.Timeout(int(backend_timeout))
            )
        super().__init__(origin + "/query", headers, client, **kwargs)

    def get_trackers(
        self, cursor: Union[Optional[Any], UnsetType] = UNSET, **kwargs: Any
    ) -> GetTrackers:
        query = gql("""
            query GetTrackers($cursor: Cursor) {
              me {
                trackers(cursor: $cursor) {
                  results {
                    ...trackerDetails
                  }
                  cursor
                }
              }
            }

            fragment trackerDetails on Tracker {
              id
              rid
              name
              description
              visibility
              updated
              defaultACL {
                browse
              }
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {"cursor": cursor}
        response = self.execute(
            query=query, operation_name="GetTrackers", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetTrackers.model_validate(data)

    def get_tracker(self, rid: str, **kwargs: Any) -> GetTracker:
        query = gql("""
            query GetTracker($rid: ID!) {
              tracker(rid: $rid) {
                ...trackerDetails
              }
            }

            fragment trackerDetails on Tracker {
              id
              rid
              name
              description
              visibility
              updated
              defaultACL {
                browse
              }
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {"rid": rid}
        response = self.execute(
            query=query, operation_name="GetTracker", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetTracker.model_validate(data)

    def create_tracker(
        self, name: str, description: str, visibility: Visibility, **kwargs: Any
    ) -> CreateTracker:
        query = gql("""
            mutation CreateTracker($name: String!, $description: String!, $visibility: Visibility!) {
              tracker: createTracker(
                name: $name
                description: $description
                visibility: $visibility
              ) {
                ...trackerDetails
              }
            }

            fragment trackerDetails on Tracker {
              id
              rid
              name
              description
              visibility
              updated
              defaultACL {
                browse
              }
              owner {
                __typename
                canonicalName
              }
            }
            """)
        variables: dict[str, object] = {
            "name": name,
            "description": description,
            "visibility": visibility,
        }
        response = self.execute(
            query=query, operation_name="CreateTracker", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return CreateTracker.model_validate(data)

    def delete_tracker(self, tracker_id: int, **kwargs: Any) -> DeleteTracker:
        query = gql("""
            mutation DeleteTracker($trackerId: Int!) {
              deleteTracker(id: $trackerId) {
                id
              }
            }
            """)
        variables: dict[str, object] = {"trackerId": tracker_id}
        response = self.execute(
            query=query, operation_name="DeleteTracker", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return DeleteTracker.model_validate(data)

    def get_ticket_comments(
        self, username: str, tracker: str, ticket_id: int, **kwargs: Any
    ) -> GetTicketComments:
        query = gql("""
            query GetTicketComments($username: String!, $tracker: String!, $ticketId: Int!) {
              user(username: $username) {
                tracker(name: $tracker) {
                  id
                  rid
                  ticket(id: $ticketId) {
                    id
                    events {
                      results {
                        changes {
                          __typename
                          ... on Comment {
                            text
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
            """)
        variables: dict[str, object] = {
            "username": username,
            "tracker": tracker,
            "ticketId": ticket_id,
        }
        response = self.execute(
            query=query,
            operation_name="GetTicketComments",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return GetTicketComments.model_validate(data)

    def submit_comment(
        self,
        tracker_id: int,
        ticket_id: int,
        comment: SubmitCommentInput,
        **kwargs: Any,
    ) -> SubmitComment:
        query = gql("""
            mutation SubmitComment($trackerId: Int!, $ticketId: Int!, $comment: SubmitCommentInput!) {
              submitComment(trackerId: $trackerId, ticketId: $ticketId, input: $comment) {
                id
              }
            }
            """)
        variables: dict[str, object] = {
            "trackerId": tracker_id,
            "ticketId": ticket_id,
            "comment": comment,
        }
        response = self.execute(
            query=query, operation_name="SubmitComment", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return SubmitComment.model_validate(data)

    def create_user_webhook(
        self, payload: str, url: str, **kwargs: Any
    ) -> CreateUserWebhook:
        query = gql("""
            mutation CreateUserWebhook($payload: String!, $url: String!) {
              webhook: createUserWebhook(
                config: {url: $url, events: [TRACKER_UPDATE, TRACKER_DELETED], query: $payload}
              ) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {"payload": payload, "url": url}
        response = self.execute(
            query=query,
            operation_name="CreateUserWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return CreateUserWebhook.model_validate(data)

    def delete_user_webhook(self, id: int, **kwargs: Any) -> DeleteUserWebhook:
        query = gql("""
            mutation DeleteUserWebhook($id: Int!) {
              deleteUserWebhook(id: $id) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query,
            operation_name="DeleteUserWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return DeleteUserWebhook.model_validate(data)

    def create_tracker_webhook(
        self, tracker_id: int, payload: str, url: str, **kwargs: Any
    ) -> CreateTrackerWebhook:
        query = gql("""
            mutation CreateTrackerWebhook($trackerId: Int!, $payload: String!, $url: String!) {
              webhook: createTrackerWebhook(
                trackerId: $trackerId
                config: {url: $url, events: [TICKET_CREATED, EVENT_CREATED], query: $payload}
              ) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {
            "trackerId": tracker_id,
            "payload": payload,
            "url": url,
        }
        response = self.execute(
            query=query,
            operation_name="CreateTrackerWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return CreateTrackerWebhook.model_validate(data)

    def delete_tracker_webhook(self, id: int, **kwargs: Any) -> DeleteTrackerWebhook:
        query = gql("""
            mutation DeleteTrackerWebhook($id: Int!) {
              deleteTrackerWebhook(id: $id) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query,
            operation_name="DeleteTrackerWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return DeleteTrackerWebhook.model_validate(data)

    def event_webhook(self, **kwargs: Any) -> EventWebhook:
        query = gql("""
            query EventWebhook {
              webhook {
                __typename
                uuid
                event
                date
                ... on TrackerEvent {
                  tracker {
                    id
                    name
                    description
                    visibility
                  }
                }
                ... on TicketEvent {
                  ticket {
                    id
                    subject
                    tracker {
                      id
                      name
                    }
                    submitter {
                      __typename
                      canonicalName
                      ... on User {
                        username
                      }
                      ... on EmailAddress {
                        mailbox
                        name
                      }
                      ... on ExternalUser {
                        externalId
                        externalUrl
                      }
                    }
                  }
                }
                ... on EventCreated {
                  newEvent {
                    ticket {
                      id
                      subject
                      tracker {
                        id
                      }
                    }
                    changes {
                      __typename
                      eventType
                      ... on Comment {
                        author {
                          __typename
                          canonicalName
                          ... on User {
                            username
                          }
                          ... on EmailAddress {
                            mailbox
                            name
                          }
                          ... on ExternalUser {
                            externalId
                            externalUrl
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
            """)
        variables: dict[str, object] = {}
        response = self.execute(
            query=query, operation_name="EventWebhook", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return EventWebhook.model_validate(data)

    get_trackers_query = "query GetTrackers($cursor: Cursor) {\n  me {\n    trackers(cursor: $cursor) {\n      results {\n        ...trackerDetails\n      }\n      cursor\n    }\n  }\n}"
    get_tracker_query = "query GetTracker($rid: ID!) {\n  tracker(rid: $rid) {\n    ...trackerDetails\n  }\n}"
    create_tracker_query = "mutation CreateTracker($name: String!, $description: String!, $visibility: Visibility!) {\n  tracker: createTracker(\n    name: $name\n    description: $description\n    visibility: $visibility\n  ) {\n    ...trackerDetails\n  }\n}"
    delete_tracker_query = "mutation DeleteTracker($trackerId: Int!) {\n  deleteTracker(id: $trackerId) {\n    id\n  }\n}"
    get_ticket_comments_query = "query GetTicketComments($username: String!, $tracker: String!, $ticketId: Int!) {\n  user(username: $username) {\n    tracker(name: $tracker) {\n      id\n      rid\n      ticket(id: $ticketId) {\n        id\n        events {\n          results {\n            changes {\n              __typename\n              ... on Comment {\n                text\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}"
    submit_comment_query = "mutation SubmitComment($trackerId: Int!, $ticketId: Int!, $comment: SubmitCommentInput!) {\n  submitComment(trackerId: $trackerId, ticketId: $ticketId, input: $comment) {\n    id\n  }\n}"
    create_user_webhook_query = "mutation CreateUserWebhook($payload: String!, $url: String!) {\n  webhook: createUserWebhook(\n    config: {url: $url, events: [TRACKER_UPDATE, TRACKER_DELETED], query: $payload}\n  ) {\n    __typename\n    id\n  }\n}"
    delete_user_webhook_query = "mutation DeleteUserWebhook($id: Int!) {\n  deleteUserWebhook(id: $id) {\n    __typename\n    id\n  }\n}"
    create_tracker_webhook_query = "mutation CreateTrackerWebhook($trackerId: Int!, $payload: String!, $url: String!) {\n  webhook: createTrackerWebhook(\n    trackerId: $trackerId\n    config: {url: $url, events: [TICKET_CREATED, EVENT_CREATED], query: $payload}\n  ) {\n    __typename\n    id\n  }\n}"
    delete_tracker_webhook_query = "mutation DeleteTrackerWebhook($id: Int!) {\n  deleteTrackerWebhook(id: $id) {\n    __typename\n    id\n  }\n}"
    event_webhook_query = "query EventWebhook {\n  webhook {\n    __typename\n    uuid\n    event\n    date\n    ... on TrackerEvent {\n      tracker {\n        id\n        name\n        description\n        visibility\n      }\n    }\n    ... on TicketEvent {\n      ticket {\n        id\n        subject\n        tracker {\n          id\n          name\n        }\n        submitter {\n          __typename\n          canonicalName\n          ... on User {\n            username\n          }\n          ... on EmailAddress {\n            mailbox\n            name\n          }\n          ... on ExternalUser {\n            externalId\n            externalUrl\n          }\n        }\n      }\n    }\n    ... on EventCreated {\n      newEvent {\n        ticket {\n          id\n          subject\n          tracker {\n            id\n          }\n        }\n        changes {\n          __typename\n          eventType\n          ... on Comment {\n            author {\n              __typename\n              canonicalName\n              ... on User {\n                username\n              }\n              ... on EmailAddress {\n                mailbox\n                name\n              }\n              ... on ExternalUser {\n                externalId\n                externalUrl\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}"
