"""
Stock Service for AidePlus
Handles stock-related operations and queries
"""

import logging
from peewee import fn, JOIN

from median.models import Stock, Magasin, Seuil
from median.constant import EcoType

logger = logging.getLogger("median.stock")


class StockService:
    """Service for handling stock operations"""

    def get_stock_info(self, product_reference, fraction, min_quantity=0):
        """
        Get stock information for a product reference and fraction

        Args:
            product_reference: Product reference code
            fraction: Product fraction
            min_quantity: Minimum quantity filter (currently not implemented)

        Returns:
            Dictionary containing stock information and threshold status
        """
        if product_reference is None or fraction is None:
            logger.error(f"Stock asked with missing info ! ref:[{product_reference}], fraction : [{fraction}]")
            return 0

        stock_query = (
            Stock.select(Stock.adresse, fn.SUM(Stock.quantite).alias("total_quantity"))
            .join(Magasin, JOIN.INNER, on=(Magasin.mag == Stock.magasin))
            .where(
                (Magasin.eco_type == EcoType.Externe.value)
                & (Stock.reference == product_reference)
                & (Stock.fraction == fraction)
            )
            .group_by(Stock.adresse)
        )

        has_threshold = (
            Seuil.get_or_none((Seuil.reference == product_reference) & (Seuil.fraction == fraction)) is not None
        )

        if min_quantity > 0:
            # TODO: This line won't work anymore - needs to be implemented properly
            # stock_query = stock_query.having(fn.SUM(Stock.quantite) >= min_quantity)
            pass

        return {
            "stock": [{"adr": stock.adresse, "total": stock.total_quantity} for stock in stock_query],
            "threshold": has_threshold,
        }

    def get_stock_info_with_brugge_fix(self, product_reference, fraction):
        """
        Get stock information with Brugge fix - placeholder for now

        Args:
            product_reference: Product reference code
            fraction: Product fraction

        Returns:
            Stock information with Brugge-specific fixes applied
        """
        # TODO: Implement Brugge-specific stock fix logic
        logger.warning(
            f"get_stock_info_with_brugge_fix not implemented for ref={product_reference}, fraction={fraction}"
        )
        return None

    def get_stock_with_fix(self, serial_code):
        """
        Get stock with fix for serial code management

        Args:
            serial_code: Serial code of the stock item

        Returns:
            Stock object with fixes applied
        """
        try:
            contenantWithMaxStock = Stock.select(Stock.contenant).where(
                Stock.serial.contains(fn.LEFT(serial_code, 10)) & (Stock.magasin == "SHV")
            )

            lostStock = (
                Stock.select(Stock)
                .where(
                    (Stock.contenant.in_(contenantWithMaxStock))
                    & (fn.RIGHT(Stock.serial, 3) >= fn.RIGHT(serial_code, 3))
                    & (
                        fn.RIGHT(Stock.serial, 3)
                        < fn.RIGHT(serial_code, 3)
                        + (
                            Stock.select(fn.MAX(Stock.quantite)).where(
                                Stock.serial.contains(fn.LEFT(serial_code, 10)) & (Stock.magasin == "SHV")
                            )
                        ).scalar()
                    )
                )
                .order_by(+Stock.serial)
                .get_or_none()
            )

            return lostStock
        except Exception as e:
            logger.error(f"Error in get_stock_with_fix for serial={serial_code}: {str(e)}")
            return None
