from typing import override

from bb_integrations_lib.gravitate.sd_api import GravitateSDAPI
from bb_integrations_lib.protocols.pipelines import Step
from loguru import logger


class MarkInvoicesExportedStep(Step):
    """Mark invoices as exported in S&D after successful upload."""

    @override
    def __init__(
        self,
        sd_client: GravitateSDAPI,
        *args,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        self.sd_client = sd_client

    def describe(self) -> str:
        return "Mark freight invoices as exported"

    async def execute(self, i) -> None:
        invoice_numbers = self.pipeline_context.extra_data.get(
            "exported_invoice_numbers", []
        )
        if not invoice_numbers:
            logger.info("No invoices to mark as exported")
            return None

        try:
            resp = await self.sd_client.mark_invoices_exported(invoice_numbers)
            if resp.status_code != 200:
                logger.warning(f"Failed to mark invoices as exported: {resp.json()}")
            else:
                logger.info(f"Marked {len(invoice_numbers)} invoices as exported")
        except Exception as e:
            logger.warning(f"Error marking invoices as exported: {e}")

        return None
