from typing import Any, Dict, Optional, Union
import logging
from app.services.external_api.tcgplayer.base_tcgplayer_service import BaseTCGPlayerService
import os

logger = logging.getLogger(__name__)

class OrderManagementService(BaseTCGPlayerService):
    ORDER_MANAGEMENT_BASE_URL = "https://order-management-api.tcgplayer.com/orders"
    
    def __init__(self):
        super().__init__()
        self.base_url = self.ORDER_MANAGEMENT_BASE_URL
        self.API_VERSION: str = "?api-version=2.0"
        self.SELLER_KEY: str = "e576ed4c"
        
        self.order_search_endpoint = f"/search{self.API_VERSION}"
        self.packing_slip_endpoint = f"/packing-slips/export{self.API_VERSION}"
        self.pull_sheet_endpoint = f"/pull-sheets/export{self.API_VERSION}"
        self.shipping_endpoint = f"/shipping/export{self.API_VERSION}"
    
    
    async def get_orders(self):
        search_from = 0
        orders = []
        while True:
            payload = {
                "searchRange": "LastThreeMonths",
                "filters": {
                "sellerKey": self.SELLER_KEY
            },
            "sortBy": [
                {"sortingType": "orderStatus", "direction": "ascending"},
                {"sortingType": "orderDate", "direction": "descending"}
            ],
            "from": search_from,
                "size": 25
            }
            response = await self._make_request("POST", self.order_search_endpoint, data=payload, headers=self._get_headers("POST", "application/json"), auth_required=True)
            if len(response.get("orders")) == 0:
                break
            search_from += 25
            orders.extend(response.get("orders"))
        return orders
    
    async def get_order(self, order_id: str):
        response = await self._make_request("GET", f"{self.ORDER_MANAGEMENT_BASE_URL}/{order_id}{self.API_VERSION}")
        return response
    
    async def get_packing_slip(self, order_ids: list[str]):
        payload = {
            "sortingType": "byRelease",
            "format": "default",
            "timezoneOffset": -4,
            "orderNumbers": order_ids
        }
        response = await self._make_request("POST", self.packing_slip_endpoint, data=payload, headers=self._get_headers("POST", "application/json"), auth_required=True, download_file=True)
        return response
    async def get_pull_sheet(self, order_ids: list[str]):
        payload = {
            "orderNumbers": order_ids,
            "timezoneOffset": -4
        }
        response = await self._make_request("POST", self.pull_sheet_endpoint, data=payload, headers=self._get_headers("POST", "application/json"), auth_required=True, download_file=True)
        return response
    
    async def get_shipping_csv(self, order_ids: list[str]):
        payload = {
            "orderNumbers": order_ids,
            "timezoneOffset": -4
        }
        response = await self._make_request("POST", self.shipping_endpoint, data=payload, headers=self._get_headers("POST", "application/json"), auth_required=True, download_file=True)
        return response
    
    async def save_file(self, file_data: bytes, file_name: str) -> str:
        if not os.path.exists("app/data/cache/tcgplayer/orders"):
            os.makedirs("app/data/cache/tcgplayer/orders")
        file_path = f"app/data/cache/tcgplayer/orders/{file_name}"
        with open(file_path, "wb") as f:
            f.write(file_data)
        return file_path