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

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_list import CreateList
from .create_list_webhook import CreateListWebhook
from .create_tool import CreateTool
from .create_user_webhook import CreateUserWebhook
from .delete_list import DeleteList
from .delete_list_webhook import DeleteListWebhook
from .delete_user_webhook import DeleteUserWebhook
from .enums import ToolIcon, Visibility
from .event_webhook import EventWebhook
from .get_list import GetList
from .get_list_by_name import GetListByName
from .get_lists import GetLists
from .get_patchset import GetPatchset
from .update_tool import UpdateTool


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


class ListsClient(BaseClient):
    def __init__(self, auth=None, headers=None, client=None, **kwargs):
        origin = cfg("lists.sr.ht", "api-origin", default=get_origin("lists.sr.ht"))
        if auth is None:
            auth = InternalAuth()
        headers = {**auth.headers, "User-Agent": "lists.sr.ht frontend"}
        if has_request_context():
            headers["X-Forwarded-For"] = ", ".join(request.access_route)
        if not client:
            backend_timeout = cfg("lists.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_lists(
        self, cursor: Union[Optional[Any], UnsetType] = UNSET, **kwargs: Any
    ) -> GetLists:
        query = gql("""
            query GetLists($cursor: Cursor) {
              me {
                lists(cursor: $cursor) {
                  results {
                    id
                    rid
                    name
                    description
                    updated
                    owner {
                      __typename
                      canonicalName
                    }
                  }
                  cursor
                }
              }
            }
            """)
        variables: dict[str, object] = {"cursor": cursor}
        response = self.execute(
            query=query, operation_name="GetLists", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetLists.model_validate(data)

    def get_list_by_name(self, list_name: str, **kwargs: Any) -> GetListByName:
        query = gql("""
            query GetListByName($listName: String!) {
              me {
                mailingList: list(name: $listName) {
                  ...listDetails
                }
              }
            }

            fragment listDetails on MailingList {
              id
              rid
              name
              description
              visibility
              defaultACL {
                browse
              }
            }
            """)
        variables: dict[str, object] = {"listName": list_name}
        response = self.execute(
            query=query, operation_name="GetListByName", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetListByName.model_validate(data)

    def get_list(self, rid: str, **kwargs: Any) -> GetList:
        query = gql("""
            query GetList($rid: ID!) {
              mailingList: list(rid: $rid) {
                ...listDetails
              }
            }

            fragment listDetails on MailingList {
              id
              rid
              name
              description
              visibility
              defaultACL {
                browse
              }
            }
            """)
        variables: dict[str, object] = {"rid": rid}
        response = self.execute(
            query=query, operation_name="GetList", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetList.model_validate(data)

    def get_patchset(self, id: int, **kwargs: Any) -> GetPatchset:
        query = gql("""
            query GetPatchset($id: Int!) {
              patchset(id: $id) {
                subject
                prefix
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query, operation_name="GetPatchset", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return GetPatchset.model_validate(data)

    def create_list(
        self, name: str, description: str, visibility: Visibility, **kwargs: Any
    ) -> CreateList:
        query = gql("""
            mutation CreateList($name: String!, $description: String!, $visibility: Visibility!) {
              mailingList: createMailingList(
                name: $name
                description: $description
                visibility: $visibility
              ) {
                id
                rid
                name
                description
                visibility
                defaultACL {
                  browse
                }
              }
            }
            """)
        variables: dict[str, object] = {
            "name": name,
            "description": description,
            "visibility": visibility,
        }
        response = self.execute(
            query=query, operation_name="CreateList", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return CreateList.model_validate(data)

    def create_tool(
        self, patchset_id: int, details: str, icon: ToolIcon, **kwargs: Any
    ) -> CreateTool:
        query = gql("""
            mutation CreateTool($patchsetID: Int!, $details: String!, $icon: ToolIcon!) {
              createTool(patchsetID: $patchsetID, details: $details, icon: $icon) {
                id
              }
            }
            """)
        variables: dict[str, object] = {
            "patchsetID": patchset_id,
            "details": details,
            "icon": icon,
        }
        response = self.execute(
            query=query, operation_name="CreateTool", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return CreateTool.model_validate(data)

    def update_tool(
        self, tool_id: int, details: str, icon: ToolIcon, **kwargs: Any
    ) -> UpdateTool:
        query = gql("""
            mutation UpdateTool($toolID: Int!, $details: String!, $icon: ToolIcon!) {
              updateTool(id: $toolID, details: $details, icon: $icon) {
                id
              }
            }
            """)
        variables: dict[str, object] = {
            "toolID": tool_id,
            "details": details,
            "icon": icon,
        }
        response = self.execute(
            query=query, operation_name="UpdateTool", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return UpdateTool.model_validate(data)

    def delete_list(self, id: int, **kwargs: Any) -> DeleteList:
        query = gql("""
            mutation DeleteList($id: Int!) {
              deleteMailingList(id: $id) {
                id
              }
            }
            """)
        variables: dict[str, object] = {"id": id}
        response = self.execute(
            query=query, operation_name="DeleteList", variables=variables, **kwargs
        )
        data = self.get_data(response)
        return DeleteList.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: [LIST_UPDATED, LIST_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_list_webhook(
        self, list_id: int, url: str, payload: str, **kwargs: Any
    ) -> CreateListWebhook:
        query = gql("""
            mutation CreateListWebhook($listId: Int!, $url: String!, $payload: String!) {
              webhook: createMailingListWebhook(
                listId: $listId
                config: {url: $url, query: $payload, events: [EMAIL_RECEIVED, PATCHSET_RECEIVED]}
              ) {
                __typename
                id
              }
            }
            """)
        variables: dict[str, object] = {
            "listId": list_id,
            "url": url,
            "payload": payload,
        }
        response = self.execute(
            query=query,
            operation_name="CreateListWebhook",
            variables=variables,
            **kwargs,
        )
        data = self.get_data(response)
        return CreateListWebhook.model_validate(data)

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

    def event_webhook(self, **kwargs: Any) -> EventWebhook:
        query = gql("""
            query EventWebhook {
              webhook {
                __typename
                uuid
                event
                date
                ... on MailingListEvent {
                  mailingList: list {
                    id
                    rid
                    name
                    description
                    visibility
                  }
                }
                ... on EmailEvent {
                  email {
                    id
                    mailingList: list {
                      id
                    }
                    messageID
                    subject
                    sender {
                      __typename
                      canonicalName
                      ... on User {
                        username
                      }
                      ... on Mailbox {
                        name
                      }
                    }
                    patch {
                      trailers {
                        name
                        value
                      }
                    }
                    patchset {
                      id
                    }
                  }
                }
                ... on PatchsetEvent {
                  patchset {
                    id
                    subject
                    prefix
                    version
                    mailingList: list {
                      id
                    }
                    thread {
                      root {
                        messageID
                        reply_to: header(want: "In-Reply-To")
                      }
                    }
                    patches {
                      results {
                        subject
                        messageID
                        patchset {
                          id
                        }
                        sender {
                          __typename
                          canonicalName
                          ... on User {
                            username
                          }
                          ... on Mailbox {
                            name
                          }
                        }
                        patch {
                          prefix
                          trailers {
                            name
                            value
                          }
                        }
                      }
                    }
                    submitter {
                      __typename
                      ... on User {
                        name: canonicalName
                        address: email
                      }
                      ... on Mailbox {
                        name
                        address
                      }
                    }
                  }
                }
              }
            }
            """)
        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_lists_query = "query GetLists($cursor: Cursor) {\n  me {\n    lists(cursor: $cursor) {\n      results {\n        id\n        rid\n        name\n        description\n        updated\n        owner {\n          __typename\n          canonicalName\n        }\n      }\n      cursor\n    }\n  }\n}"
    get_list_by_name_query = "query GetListByName($listName: String!) {\n  me {\n    mailingList: list(name: $listName) {\n      ...listDetails\n    }\n  }\n}"
    get_list_query = "query GetList($rid: ID!) {\n  mailingList: list(rid: $rid) {\n    ...listDetails\n  }\n}"
    get_patchset_query = "query GetPatchset($id: Int!) {\n  patchset(id: $id) {\n    subject\n    prefix\n  }\n}"
    create_list_query = "mutation CreateList($name: String!, $description: String!, $visibility: Visibility!) {\n  mailingList: createMailingList(\n    name: $name\n    description: $description\n    visibility: $visibility\n  ) {\n    id\n    rid\n    name\n    description\n    visibility\n    defaultACL {\n      browse\n    }\n  }\n}"
    create_tool_query = "mutation CreateTool($patchsetID: Int!, $details: String!, $icon: ToolIcon!) {\n  createTool(patchsetID: $patchsetID, details: $details, icon: $icon) {\n    id\n  }\n}"
    update_tool_query = "mutation UpdateTool($toolID: Int!, $details: String!, $icon: ToolIcon!) {\n  updateTool(id: $toolID, details: $details, icon: $icon) {\n    id\n  }\n}"
    delete_list_query = "mutation DeleteList($id: Int!) {\n  deleteMailingList(id: $id) {\n    id\n  }\n}"
    create_user_webhook_query = "mutation CreateUserWebhook($payload: String!, $url: String!) {\n  webhook: createUserWebhook(\n    config: {url: $url, events: [LIST_UPDATED, LIST_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_list_webhook_query = "mutation CreateListWebhook($listId: Int!, $url: String!, $payload: String!) {\n  webhook: createMailingListWebhook(\n    listId: $listId\n    config: {url: $url, query: $payload, events: [EMAIL_RECEIVED, PATCHSET_RECEIVED]}\n  ) {\n    __typename\n    id\n  }\n}"
    delete_list_webhook_query = "mutation DeleteListWebhook($id: Int!) {\n  deleteMailingListWebhook(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 MailingListEvent {\n      mailingList: list {\n        id\n        rid\n        name\n        description\n        visibility\n      }\n    }\n    ... on EmailEvent {\n      email {\n        id\n        mailingList: list {\n          id\n        }\n        messageID\n        subject\n        sender {\n          __typename\n          canonicalName\n          ... on User {\n            username\n          }\n          ... on Mailbox {\n            name\n          }\n        }\n        patch {\n          trailers {\n            name\n            value\n          }\n        }\n        patchset {\n          id\n        }\n      }\n    }\n    ... on PatchsetEvent {\n      patchset {\n        id\n        subject\n        prefix\n        version\n        mailingList: list {\n          id\n        }\n        thread {\n          root {\n            messageID\n            reply_to: header(want: "In-Reply-To")\n          }\n        }\n        patches {\n          results {\n            subject\n            messageID\n            patchset {\n              id\n            }\n            sender {\n              __typename\n              canonicalName\n              ... on User {\n                username\n              }\n              ... on Mailbox {\n                name\n              }\n            }\n            patch {\n              prefix\n              trailers {\n                name\n                value\n              }\n            }\n          }\n        }\n        submitter {\n          __typename\n          ... on User {\n            name: canonicalName\n            address: email\n          }\n          ... on Mailbox {\n            name\n            address\n          }\n        }\n      }\n    }\n  }\n}'
