import uuid
from bb_integrations_lib.gravitate.sd_api import GravitateSDAPI
from bb_integrations_lib.models.pipeline_structs import NoPipelineData
from bb_integrations_lib.shared.model import ERPStatus, SDSetOrderExportStatusRequest, \
    SDGetUnexportedOrdersResponse
from bb_integrations_lib.protocols.pipelines import Step
from loguru import logger


class BBDSetExportOrderStatus(Step):
    def __init__(self,
                 sd_client: GravitateSDAPI,
                 step_key: str | None = uuid.uuid4().hex,
                 global_status_override: ERPStatus | None = None,
                 *args,  **kwargs):
        super().__init__(*args,  **kwargs)
        self.step_key = step_key
        self.sd_client = sd_client
        self.global_status_override = global_status_override

    def describe(self):
        return "Set Order Export Status in BBD"

    async def execute(self, orders: list[SDGetUnexportedOrdersResponse]) -> list[SDGetUnexportedOrdersResponse]:
        request = self.format_set_order_status_request(orders)
        logger.info("Order Status Request")
        logger.info(request)
        response = await self.sd_client.bulk_set_export_order_status(request)
        response.raise_for_status()
        return orders

    def format_set_order_status_request(self, orders: list[SDGetUnexportedOrdersResponse]) -> list[SDSetOrderExportStatusRequest]:
        if orders is None:
            raise NoPipelineData("Did not find any new orders to export")
        reqs = []
        for order in orders:
            if self.global_status_override:
                order.export_status = self.global_status_override
            req = SDSetOrderExportStatusRequest(
                order_id = order.order_id,
                status = order.export_status,
                error=order.error_message,
            )
            reqs.append(req)
        return reqs





