from __future__ import annotations

import httpx

from .models import (
    MessageCreateRequest,
    MessageList,
    PaginatedMessageListList,
    PaginatedTicketListList,
    PatchedTicketUpdateRequest,
    TicketCreateRequest,
    TicketDetail,
)


class SupportSupportAPI:
    """API endpoints for Support."""

    def __init__(self, client: httpx.AsyncClient):
        """Initialize sub-client with shared httpx client."""
        self._client = client

    async def tickets_list(
        self,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedTicketListList]:
        """
        List support tickets

        ViewSet for support ticket operations.
        """
        url = "/api/support/tickets/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedTicketListList.model_validate(response.json())


    async def tickets_create(self, data: TicketCreateRequest) -> TicketDetail:
        """
        Create a support ticket

        Override to return TicketDetailSerializer in the response.
        """
        url = "/api/support/tickets/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return TicketDetail.model_validate(response.json())


    async def tickets_retrieve(self, id: str) -> TicketDetail:
        """
        Get ticket details

        ViewSet for support ticket operations.
        """
        url = f"/api/support/tickets/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return TicketDetail.model_validate(response.json())


    async def tickets_partial_update(
        self,
        id: str,
        data: PatchedTicketUpdateRequest | None = None,
    ) -> TicketDetail:
        """
        Update ticket status

        ViewSet for support ticket operations.
        """
        url = f"/api/support/tickets/{id}/"
        _json = data.model_dump(mode="json", exclude_unset=True, exclude_none=True) if data else None
        response = await self._client.patch(url, json=_json)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return TicketDetail.model_validate(response.json())


    async def tickets_destroy(self, id: str) -> None:
        """
        ViewSet for support ticket operations.
        """
        url = f"/api/support/tickets/{id}/"
        response = await self._client.delete(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return None


    async def tickets_close_create(self, id: str) -> TicketDetail:
        """
        Close a ticket

        Close a ticket (terminal state).
        """
        url = f"/api/support/tickets/{id}/close/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return TicketDetail.model_validate(response.json())


    async def tickets_reopen_create(self, id: str) -> TicketDetail:
        """
        Reopen a resolved/closed ticket

        Reopen a resolved or closed ticket.
        """
        url = f"/api/support/tickets/{id}/reopen/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return TicketDetail.model_validate(response.json())


    async def tickets_messages_list(
        self,
        ticket_id: str,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedMessageListList]:
        """
        List messages in a ticket

        ViewSet for ticket messages. Nested under tickets.
        """
        url = f"/api/support/tickets/{ticket_id}/messages/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedMessageListList.model_validate(response.json())


    async def tickets_messages_create(
        self,
        ticket_id: str,
        data: MessageCreateRequest,
    ) -> MessageList:
        """
        Send a message in a ticket

        ViewSet for ticket messages. Nested under tickets.
        """
        url = f"/api/support/tickets/{ticket_id}/messages/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return MessageList.model_validate(response.json())


    async def tickets_messages_retrieve(self, id: str, ticket_id: str) -> MessageList:
        """
        Get message detail

        ViewSet for ticket messages. Nested under tickets.
        """
        url = f"/api/support/tickets/{ticket_id}/messages/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return MessageList.model_validate(response.json())


