"""Orders resource — place and manage orders."""
from __future__ import annotations

from typing import Optional
from .._http import HttpClient


class OrderResource:
    def __init__(self, http: HttpClient):
        self._http = http

    def create(self, product_id: str, quantity: int = 1) -> dict:
        """
        Place a new order.

        Args:
            product_id: Product UUID.
            quantity:   Number of units (default 1).

        Returns:
            dict: ``{ orderId, productName, status, isService, totalCost, items }``

        Raises:
            InsufficientBalanceError: If the account balance is too low.
            ValidationError:          If product is out of stock.
        """
        return self._http.post("/v1/order/create", {
            "productId": product_id,
            "quantity": quantity,
        })

    def get(self, order_id: str) -> dict:
        """
        Get full order details including delivery items if completed.

        Args:
            order_id: Order ID string (12-char alphanumeric).
        """
        return self._http.get(f"/v1/order/{order_id}")

    def messages(self, order_id: str) -> dict:
        """
        Get all chat messages for a service order (poll-based).

        Args:
            order_id: Order ID.

        Returns:
            dict: ``{ orderId, orderStatus, totalMessages, messages[] }``
        """
        return self._http.get(f"/v1/order/{order_id}/messages")

    def send_message(
        self,
        order_id: str,
        message: Optional[str] = None,
        file_url: Optional[str] = None,
    ) -> dict:
        """
        Send a chat message to staff on a service order.

        Args:
            order_id:  Order ID.
            message:   Text content (optional if file_url provided).
            file_url:  File URL (optional if message provided).

        Returns:
            dict: ``{ messageId, createdAt }``
        """
        body: dict = {"orderId": order_id}
        if message is not None:
            body["message"] = message
        if file_url is not None:
            body["fileUrl"] = file_url
        return self._http.post("/v1/order/chat/send", body)

    def reopen(self, order_id: str) -> dict:
        """
        Reopen a completed service order under its active warranty.

        Args:
            order_id: Order ID.

        Returns:
            dict: ``{ orderId, isReopened, warrantyEndsAt }``

        Raises:
            ValidationError: If warranty has expired or order is not completed.
        """
        return self._http.post(f"/v1/order/{order_id}/reopen", {})
