from __future__ import annotations

import httpx

from .models import (
    EmailAccountCreateRequest,
    EmailAccountList,
    EmailMessageList,
    EmailSendRequest,
    EmailSendResponse,
    TestConnectionResponse,
)


class SyncEmailGatewayEmailAPI:
    """Synchronous API endpoints for Email."""

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

    def accounts_list(self) -> list[EmailAccountList]:
        url = "/api/email/accounts/"
        response = 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 [EmailAccountList.model_validate(item) for item in response.json()]


    def accounts_destroy(self, id: str) -> None:
        url = f"/api/email/accounts/{id}/"
        response = 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


    def accounts_test_create(self, id: str) -> TestConnectionResponse:
        url = f"/api/email/accounts/{id}/test/"
        response = 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 TestConnectionResponse.model_validate(response.json())


    def accounts_create_create(self, data: EmailAccountCreateRequest) -> EmailAccountList:
        url = "/api/email/accounts/create/"
        response = 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 EmailAccountList.model_validate(response.json())


    def messages_list(self) -> list[EmailMessageList]:
        url = "/api/email/messages/"
        response = 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 [EmailMessageList.model_validate(item) for item in response.json()]


    def send_create(self, data: EmailSendRequest) -> EmailSendResponse:
        url = "/api/email/send/"
        response = 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 EmailSendResponse.model_validate(response.json())


