import os
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Optional

import stripe

from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.enums.enums import ListingStatusEnum, OrderStatusEnum
from app.models.listing.products import ProductListing, Product, CategoryTax, ProductCategory, ProductTax
from app.models.staff.store_model import Store
from app.models.user.order_model import UserOrder, UserOrderItem
from app.models.user.user_model import User
from app.schemas.user.order_schemas import (
    OrderCancelResponse,
    OrderCreateRequest,
    OrderItemListingSummary,
    OrderItemResponse,
    OrderPaymentConfirmRequest,
    OrderPaymentIntentResponse,
    OrderRefundRequest,
    OrderRefundResponse,
    OrderResponse,
    OrderSummary,
    OrderUpdateRequest,
    ProductSummary,
    StoreResponse,
    PricingCalculationRequest,
    PricingCalculationResponse,
    PricingItemBreakdown,
)
from app.services.user.voucher_service import VoucherService


class OrderService:
    def __init__(self, db: AsyncSession):
        self.db = db
        self.voucher_service = VoucherService(db)

    @staticmethod
    def _ensure_stripe_configured() -> str:
        api_key = os.getenv("STRIPE_SECRET_KEY")
        if not api_key:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Stripe secret key not configured"
            )
        stripe.api_key = api_key
        return api_key

    @staticmethod
    def _get_stripe_currency() -> str:
        return os.getenv("STRIPE_PAYMENT_CURRENCY", "usd")

    @staticmethod
    def _amount_to_cents(amount: float) -> int:
        quantized = Decimal(str(amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        return int(quantized * 100)

    async def _ensure_user_exists(self, user_id: int) -> User:
        stmt = select(User).where(User.user_id == user_id)
        result = await self.db.execute(stmt)
        user = result.scalar_one_or_none()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        return user

    async def _fetch_listings(self, listing_ids: List[int]) -> List[ProductListing]:
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.product).selectinload(Product.category).selectinload(ProductCategory.taxes),
                selectinload(ProductListing.product).selectinload(Product.taxes),
                selectinload(ProductListing.store),
            )
            .where(ProductListing.listing_id.in_(listing_ids))
        )
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def _load_order_for_user(self, user_id: int, order_id: int) -> UserOrder:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store)
                .selectinload(Store.chain),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store)
                .selectinload(Store.chain),
            )
            .where(
                UserOrder.order_id == order_id,
                UserOrder.user_id == user_id,
            )
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()
        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )
        return order

    async def _get_store_state(self, store_id: int) -> Optional[str]:
        """
        Get the store's state.
        Returns state code (e.g., 'SINDH', 'PUNJAB') or None if not found.
        """
        stmt = select(Store).where(Store.store_id == store_id)
        result = await self.db.execute(stmt)
        store = result.scalar_one_or_none()
        
        if store and store.state:
            # Normalize state code to uppercase (e.g., 'sindh' -> 'SINDH')
            return store.state.upper().strip()
        return None
    
    @staticmethod
    def _normalize_state_for_matching(state: str) -> str:
        """
        Normalize state code for matching. Handles abbreviations and full names.
        Returns normalized state code.
        """
        if not state:
            return ""
        normalized = state.upper().strip()
        
        # Common US state abbreviations to full names mapping
        state_mapping = {
            "FL": "FLORIDA",
            "CA": "CALIFORNIA",
            "NY": "NEW YORK",
            "TX": "TEXAS",
            "IL": "ILLINOIS",
            "PA": "PENNSYLVANIA",
            "OH": "OHIO",
            "GA": "GEORGIA",
            "NC": "NORTH CAROLINA",
            "MI": "MICHIGAN",
            "NJ": "NEW JERSEY",
            "VA": "VIRGINIA",
            "WA": "WASHINGTON",
            "AZ": "ARIZONA",
            "MA": "MASSACHUSETTS",
            "TN": "TENNESSEE",
            "IN": "INDIANA",
            "MO": "MISSOURI",
            "MD": "MARYLAND",
            "WI": "WISCONSIN",
            "CO": "COLORADO",
            "MN": "MINNESOTA",
            "SC": "SOUTH CAROLINA",
            "AL": "ALABAMA",
            "LA": "LOUISIANA",
            "KY": "KENTUCKY",
            "OR": "OREGON",
            "OK": "OKLAHOMA",
            "CT": "CONNECTICUT",
            "UT": "UTAH",
            "IA": "IOWA",
            "NV": "NEVADA",
            "AR": "ARKANSAS",
            "MS": "MISSISSIPPI",
            "KS": "KANSAS",
            "NM": "NEW MEXICO",
            "NE": "NEBRASKA",
            "WV": "WEST VIRGINIA",
            "ID": "IDAHO",
            "HI": "HAWAII",
            "NH": "NEW HAMPSHIRE",
            "ME": "MAINE",
            "MT": "MONTANA",
            "RI": "RHODE ISLAND",
            "DE": "DELAWARE",
            "SD": "SOUTH DAKOTA",
            "ND": "NORTH DAKOTA",
            "AK": "ALASKA",
            "DC": "DISTRICT OF COLUMBIA",
            "VT": "VERMONT",
            "WY": "WYOMING",
        }
        
        # If it's an abbreviation, return the full name
        if normalized in state_mapping:
            return state_mapping[normalized]
        
        # Otherwise return as-is (for full names like "FLORIDA", "SINDH", etc.)
        return normalized
    
    @staticmethod
    def _states_match(store_state: str, tax_state_code: str) -> bool:
        """
        Check if store state matches tax state code.
        Handles abbreviations, full names, and case-insensitive matching.
        Both values are normalized (abbreviations converted to full names) before comparison.
        """
        if not store_state or not tax_state_code:
            return False
        
        store_normalized = OrderService._normalize_state_for_matching(store_state)
        tax_normalized = OrderService._normalize_state_for_matching(tax_state_code)
        
        # Direct match after normalization (e.g., "FL" and "FLORIDA" both become "FLORIDA")
        return store_normalized == tax_normalized
    
    @staticmethod
    def _calculate_taxes(listing: ProductListing, unit_price: float, quantity: int, store_state: Optional[str] = None) -> float:
        """
        Calculate total tax amount for a listing based on both product taxes and category taxes for the store's state.
        Returns the total tax amount for the given quantity.
        Note: This method should only be called when taxes are already loaded via selectinload.
        """
        if not listing.product:
            return 0.0

        # Get taxes from ProductTax relationship (should be loaded via selectinload)
        # Use getattr to safely access without triggering lazy load
        product_taxes = getattr(listing.product, "taxes", []) or []

        # Get taxes from CategoryTax relationship (should be loaded via selectinload)
        category_taxes = []
        if listing.product.category:
            category_taxes = getattr(listing.product.category, "taxes", []) or []

        state_key: Optional[str] = None
        if store_state:
            state_key = store_state.upper().strip()

        # Filter product taxes by state (global if state_code is empty/null, else state-specific)
        applied_product_taxes: list[ProductTax] = []
        for tax in product_taxes:
            tax_state_code = getattr(tax, "state_code", None)
            tax_state_normalized = None
            if isinstance(tax_state_code, str):
                tax_state_normalized = tax_state_code.strip().upper()
            
            # If state_code is empty/null or "GLOBAL", it's a global tax - always apply
            if not tax_state_normalized or tax_state_normalized == "GLOBAL" or tax_state_normalized == "":
                applied_product_taxes.append(tax)
            elif state_key and OrderService._states_match(state_key, tax_state_normalized):
                # State-specific product tax - must match store state (handles abbreviations)
                applied_product_taxes.append(tax)

        # Filter category taxes by state (strict state match required, handles abbreviations)
        applied_category_taxes: list[CategoryTax] = []
        if state_key and category_taxes:
            applied_category_taxes = [
                tax
                for tax in category_taxes
                if isinstance(tax.state_code, str) and OrderService._states_match(state_key, tax.state_code.strip().upper())
            ]

        # NEW LOGIC: If product tax exists, use ONLY product tax. Otherwise, use category tax.
        use_product_taxes = len(applied_product_taxes) > 0
        use_category_taxes = len(applied_category_taxes) > 0 and not use_product_taxes

        # If no taxes at all, return 0
        if not use_product_taxes and not use_category_taxes:
            return 0.0

        # Calculate total tax amount
        total_tax_amount = 0.0

        # Apply taxes based on priority: product tax first, category tax only if no product tax
        if use_product_taxes:
            for tax in applied_product_taxes:
                tax_percent = float(tax.tax_percent)
                tax_amount = (unit_price * tax_percent / 100.0) * quantity
                total_tax_amount += tax_amount
        elif use_category_taxes:
            for tax in applied_category_taxes:
                tax_percent = float(tax.tax_percent)
                tax_amount = (unit_price * tax_percent / 100.0) * quantity
                total_tax_amount += tax_amount
        
        # Round to 2 decimals
        return float(Decimal(str(total_tax_amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
    
    @staticmethod
    def _calculate_taxes_with_breakdown(
        listing: ProductListing,
        unit_price: float,
        quantity: int,
        store_state: Optional[str] = None,
    ) -> tuple[float, list]:
        """
        Calculate total tax amount and detailed tax lines.
        Logic: If product tax exists, use ONLY product tax. Otherwise, use category tax.
        """
        if not listing.product:
            return 0.0, []

        product_taxes = getattr(listing.product, "taxes", []) or []
        category_taxes = []
        if listing.product.category:
            category_taxes = getattr(listing.product.category, "taxes", []) or []

        state_key: Optional[str] = None
        if store_state:
            state_key = store_state.upper().strip()

        # Debug logging
        print(f"\n=== TAX CALCULATION DEBUG (with breakdown) ===")
        print(f"Store state: {store_state} -> normalized: {state_key}")
        print(f"Product taxes found: {len(product_taxes)}")
        for i, tax in enumerate(product_taxes):
            tax_state_code = getattr(tax, "state_code", None)
            print(f"  Tax {i+1}: name={getattr(tax, 'tax_name', None)}, state_code={tax_state_code}, percent={getattr(tax, 'tax_percent', None)}")

        # Filter product taxes by state (global if state_code is empty/null, else state-specific)
        applied_product_taxes: list[ProductTax] = []
        for tax in product_taxes:
            tax_state_code = getattr(tax, "state_code", None)
            tax_state_normalized = None
            if isinstance(tax_state_code, str):
                tax_state_normalized = tax_state_code.strip().upper()
            
            # If state_code is empty/null or "GLOBAL", it's a global tax - always apply
            if not tax_state_normalized or tax_state_normalized == "GLOBAL" or tax_state_normalized == "":
                print(f"  -> Adding global tax: {getattr(tax, 'tax_name', None)}")
                applied_product_taxes.append(tax)
            elif state_key and OrderService._states_match(state_key, tax_state_normalized):
                # State-specific product tax - must match store state (handles abbreviations)
                print(f"  -> Adding state-specific tax (matches {state_key}): {getattr(tax, 'tax_name', None)}")
                applied_product_taxes.append(tax)
            else:
                print(f"  -> Skipping tax (state mismatch: {tax_state_normalized} != {state_key}): {getattr(tax, 'tax_name', None)}")
        
        print(f"Applied product taxes: {len(applied_product_taxes)}")

        # Filter category taxes by state (strict state match required, handles abbreviations)
        applied_category_taxes: list[CategoryTax] = []
        if state_key and category_taxes:
            applied_category_taxes = [
                tax
                for tax in category_taxes
                if isinstance(tax.state_code, str) and OrderService._states_match(state_key, tax.state_code.strip().upper())
            ]

        # NEW LOGIC: If product tax exists, use ONLY product tax. Otherwise, use category tax.
        use_product_taxes = len(applied_product_taxes) > 0
        use_category_taxes = len(applied_category_taxes) > 0 and not use_product_taxes

        print(f"Use product taxes: {use_product_taxes}, Use category taxes: {use_category_taxes}")
        print(f"===============================================\n")

        if not use_product_taxes and not use_category_taxes:
            return 0.0, []

        from app.schemas.user.order_schemas import AppliedTax

        total_tax_amount = 0.0
        applied_taxes: list[AppliedTax] = []

        # Helper to compute and append a tax line
        def add_tax_line(tax_obj, source: str):
            nonlocal total_tax_amount, applied_taxes
            tax_percent = float(tax_obj.tax_percent)
            raw_amount = (unit_price * tax_percent / 100.0) * quantity
            # Round each tax line to 2 decimals
            amount = float(Decimal(str(raw_amount)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
            total_tax_amount += amount
            
            # Get state_code for the tax line
            tax_state_code = getattr(tax_obj, "state_code", None)
            display_state_code = None
            if isinstance(tax_state_code, str) and tax_state_code.strip():
                display_state_code = tax_state_code.strip().upper()
            elif state_key:
                display_state_code = state_key
            
            applied_taxes.append(
                AppliedTax(
                    tax_name=tax_obj.tax_name,
                    tax_percent=tax_percent,
                    tax_key=getattr(tax_obj, "tax_key", None),
                    source=source,
                    state_code=display_state_code,
                    amount=amount,
                )
            )

        # Apply taxes based on priority: product tax first, category tax only if no product tax
        if use_product_taxes:
            for tax in applied_product_taxes:
                add_tax_line(tax, "PRODUCT")
        elif use_category_taxes:
            for tax in applied_category_taxes:
                add_tax_line(tax, "CATEGORY")

        return total_tax_amount, applied_taxes
    
    @staticmethod
    def _calculate_unit_price(listing: ProductListing) -> float:
        """
        Calculate the unit price for a listing at order time using the same
        discount logic shown to users:
        - Use UTC for go_live_date comparison
        - total_discount = current_discount + daily_increasing_discount_percent * days_since_go_live
        - Cap discount at 80%
        - Base price = average_price (if available) else product.base_price
        """
        # Use getattr to safely access product without triggering lazy load
        product = getattr(listing, 'product', None)
        if not product:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Listing {listing.listing_id} has no associated product"
            )
        base_price = listing.average_price if listing.average_price is not None else getattr(product, 'base_price', None)
        if base_price is None:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Listing {listing.listing_id} has no associated pricing information"
            )

        # If discount fields are missing, return base price
        if not listing.current_discount or not listing.daily_increasing_discount_percent:
            return float(Decimal(str(base_price)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))

        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()
        go_live_date = listing.go_live_date
        days_passed = 0
        if go_live_date:
            days_passed = (today_utc - go_live_date).days
            if days_passed < 0:
                days_passed = 0  # not live yet; no incremental discount

        total_discount = listing.current_discount + (listing.daily_increasing_discount_percent * days_passed)
        if total_discount > 80.0:
            total_discount = 80.0

        discounted_price = base_price * (1 - total_discount / 100.0)
        # Round to 2 decimals consistently
        return float(Decimal(str(discounted_price)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))

    async def _cancel_payment_intent(self, payment_intent_id: Optional[str]) -> None:
        if not payment_intent_id:
            return
        try:
            self._ensure_stripe_configured()
            stripe.PaymentIntent.cancel(payment_intent_id)
        except stripe.error.InvalidRequestError:
            pass

    def _build_order_response(self, order: UserOrder) -> OrderResponse:
        items: List[OrderItemResponse] = []
        subtotal = 0.0
        total_tax_amount = 0.0
        
        # Get store state for tax calculation
        store = getattr(order, 'store', None)
        store_state = getattr(store, 'state', None) if store else None
        
        for item in order.items:
            listing_summary: Optional[OrderItemListingSummary] = None
            # Use getattr to safely access listing without triggering lazy load
            listing = getattr(item, 'listing', None)
            if listing:
                # Use getattr to safely access store without triggering lazy load
                store = getattr(listing, 'store', None)
                listing_summary = OrderItemListingSummary(
                    listing_id=listing.listing_id,
                    listing_type=listing.listing_type,
                    status=listing.status,
                    go_live_date=listing.go_live_date,
                    store_id=getattr(store, 'store_id', None) if store else None,
                    store_name=getattr(store, 'store_name', None) if store else None,
                    quantity=listing.quantity,
                    best_by_date=listing.best_by_date,
                    weighted_items_prices=listing.weighted_items_prices,
                    average_price=listing.average_price,
                    current_discount=listing.current_discount,
                    daily_increasing_discount_percent=listing.daily_increasing_discount_percent,
                    hourly_increasing_discount=listing.hourly_increasing_discount,
                    weekly_schedule=listing.weekly_schedule,
                    discount_start_date=listing.discount_start_date,
                    discount_end_date=listing.discount_end_date,
                )

            # Calculate tax amount for this item
            tax_amount = 0.0
            if listing:
                tax_amount = self._calculate_taxes(listing, item.unit_price, item.quantity, store_state)
                total_tax_amount += tax_amount
                subtotal += item.total_price  # total_price is already unit_price * quantity

            # Build product summary
            product_summary = None
            product = getattr(item, 'product', None)
            if product:
                category = getattr(product, 'category', None)
                category_name = getattr(category, 'category_name', None) if category else None
                product_summary = ProductSummary(
                    product_id=product.product_id,
                    product_name=product.product_name,
                    product_description=product.product_description,
                    product_barcode=product.product_barcode,
                    product_image=product.product_image,
                    base_price=product.base_price,
                    unit=product.unit,
                    category_id=product.category_id,
                    category_name=category_name,
                )

            items.append(
                OrderItemResponse(
                    order_item_id=item.order_item_id,
                    listing_id=getattr(item, 'listing_id', None),  # Handle None for legacy data
                    product_id=item.product_id,
                    product_name=item.product.product_name if item.product else None,
                    quantity=item.quantity,
                    unit_price=item.unit_price,
                    total_price=item.total_price,
                    tax_amount=tax_amount,
                    listing=listing_summary,
                    product=product_summary,
                )
            )

        # Use getattr to safely access voucher without triggering lazy load
        voucher = getattr(order, 'voucher', None)
        voucher_code = getattr(voucher, 'code', None) if voucher else None

        # Build store response if store is available
        store_response = None
        store = getattr(order, 'store', None)
        if store:
            store_response = StoreResponse(
                store_id=store.store_id,
                store_name=store.store_name,
                store_location=store.store_location,
                store_operational_hours=store.store_operational_hours,
                state=store.state,
                chain_id=store.chain_id,
                latitude=store.latitude,
                longitude=store.longitude,
            )

        # Build order summary
        total_amount_with_taxes = subtotal + total_tax_amount
        summary = OrderSummary(
            subtotal=subtotal,
            total_tax_amount=total_tax_amount,
            total_amount=total_amount_with_taxes,
            discount_amount=order.discount_amount,
            final_amount=order.final_amount,
            has_tax=total_tax_amount > 0.0,
        )

        return OrderResponse(
            order_id=order.order_id,
            user_id=order.user_id,
            store_id=order.store_id,
            store=store_response,
            status=order.status,
            total_amount=order.total_amount,
            discount_amount=order.discount_amount,
            final_amount=order.final_amount,
            voucher_code=voucher_code,
            notes=order.notes,
            payment_intent_id=order.payment_intent_id,
            payment_status=order.payment_status,
            created_at=order.created_at,
            updated_at=order.updated_at,
            items=items,
            summary=summary,
        )


    async def create_order(
        self,
        user_id: int,
        data: OrderCreateRequest
    ) -> OrderResponse:
        await self._ensure_user_exists(user_id)
        listing_ids = [item.listing_id for item in data.items]
        listings = await self._fetch_listings(listing_ids)

        if len(listings) != len(listing_ids):
            missing_ids = set(listing_ids) - {listing.listing_id for listing in listings}
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Listings not found: {sorted(missing_ids)}"
            )
        
        store_id: Optional[int] = None
        total_amount = 0.0
        total_tax_amount = 0.0
        listing_map = {listing.listing_id: listing for listing in listings}

        for item in data.items:
            listing = listing_map[item.listing_id]

            if listing.status != ListingStatusEnum.APPROVED:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Listing {listing.listing_id} is not available for ordering"
                )

            if store_id is None:
                store_id = listing.store_id
            elif store_id != listing.store_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="All items in an order must belong to the same store"
                )

            unit_price = self._calculate_unit_price(listing)
            item_subtotal = unit_price * item.quantity
            total_amount += item_subtotal
            
        # Get store's state for tax calculation (all items are from the same store)
        store_state = await self._get_store_state(store_id) if store_id else None
        
        # Recalculate taxes with store state
        for item in data.items:
            listing = listing_map[item.listing_id]
            unit_price = self._calculate_unit_price(listing)
            # Calculate taxes for this item based on store's state
            tax_amount = self._calculate_taxes(listing, unit_price, item.quantity, store_state)
            total_tax_amount += tax_amount

        # Add taxes to total amount
        total_amount_with_taxes = total_amount + total_tax_amount
        
        discount_amount = 0.0
        voucher = None

        if data.voucher_code:
            voucher, discount_amount = await self.voucher_service.validate_and_calculate_discount(
                data.voucher_code,
                total_amount_with_taxes
            )

        final_amount = max(total_amount_with_taxes - discount_amount, 0.0)

        order = UserOrder(
            user_id=user_id,
            store_id=store_id,
            status=OrderStatusEnum.IN_PROCESS,
            total_amount=total_amount_with_taxes,  # Include taxes in total
            discount_amount=discount_amount,
            final_amount=final_amount,
            voucher_id=voucher.voucher_id if voucher else None,
            notes=data.notes,
            payment_status="PENDING",
        )

        self.db.add(order)
        await self.db.flush()  # Get order_id

        order_items = []
        for item in data.items:
            listing = listing_map[item.listing_id]
            unit_price = self._calculate_unit_price(listing)
            total_price = unit_price * item.quantity

            order_item = UserOrderItem(
                order_id=order.order_id,
                listing_id=listing.listing_id,
                product_id=listing.product_id,
                quantity=item.quantity,
                unit_price=unit_price,
                total_price=total_price,
            )
            self.db.add(order_item)
            order_items.append(order_item)

        await self.db.commit()

        await self.db.refresh(order, attribute_names=["items", "voucher", "store"])
        for item in order_items:
            await self.db.refresh(item, attribute_names=["product", "listing"])

        if voucher:
            await self.voucher_service.increment_usage(voucher)

        return self._build_order_response(order)

    async def calculate_pricing(
        self,
        user_id: int,
        data: PricingCalculationRequest
    ) -> PricingCalculationResponse:
        """
        Calculate pricing breakdown for selected products without creating an order.
        Returns detailed breakdown including subtotals, taxes, discounts, and final amount.
        """
        await self._ensure_user_exists(user_id)
        listing_ids = [item.listing_id for item in data.items]
        listings = await self._fetch_listings(listing_ids)

        if len(listings) != len(listing_ids):
            missing_ids = set(listing_ids) - {listing.listing_id for listing in listings}
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Listings not found: {sorted(missing_ids)}"
            )
        
        store_id: Optional[int] = None
        listing_map = {listing.listing_id: listing for listing in listings}
        items_breakdown: List[PricingItemBreakdown] = []
        subtotal = 0.0
        total_tax_amount = 0.0

        for item in data.items:
            listing = listing_map[item.listing_id]

            if listing.status != ListingStatusEnum.APPROVED:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Listing {listing.listing_id} is not available for ordering"
                )

            if store_id is None:
                store_id = listing.store_id
            elif store_id != listing.store_id:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="All items in an order must belong to the same store"
                )

            # Calculate unit price (with discounts)
            unit_price = self._calculate_unit_price(listing)
            item_subtotal = unit_price * item.quantity
            subtotal += item_subtotal
            
        # Get store's state for tax calculation (all items are from the same store)
        store_state = await self._get_store_state(store_id) if store_id else None
        
        # Calculate taxes with store state
        for item in data.items:
            listing = listing_map[item.listing_id]
            unit_price = self._calculate_unit_price(listing)
            # Calculate taxes for this item based on store's state,
            # and capture detailed tax lines
            tax_amount, applied_taxes = self._calculate_taxes_with_breakdown(
                listing, unit_price, item.quantity, store_state
            )
            total_tax_amount += tax_amount
            item_subtotal = unit_price * item.quantity
            item_total = item_subtotal + tax_amount

            # Get product name
            product_name = listing.product.product_name if listing.product else f"Product {listing.product_id}"

            items_breakdown.append(
                PricingItemBreakdown(
                    listing_id=listing.listing_id,
                    product_id=listing.product_id,
                    product_name=product_name,
                    quantity=item.quantity,
                    unit_price=round(unit_price, 2),
                    subtotal=round(item_subtotal, 2),
                    tax_amount=round(tax_amount, 2),
                    total=round(item_total, 2),
                    applied_taxes=applied_taxes,
                )
            )

        # Add taxes to total amount
        total_amount_with_taxes = subtotal + total_tax_amount
        
        # Validate and calculate voucher discount
        discount_amount = 0.0
        voucher_valid = False
        voucher_code = None

        if data.voucher_code:
            try:
                voucher, discount_amount = await self.voucher_service.validate_and_calculate_discount(
                    data.voucher_code,
                    total_amount_with_taxes
                )
                voucher_valid = True
                voucher_code = data.voucher_code
            except HTTPException:
                # Voucher is invalid, but we still return pricing without discount
                voucher_valid = False
                voucher_code = data.voucher_code

        final_amount = max(total_amount_with_taxes - discount_amount, 0.0)

        return PricingCalculationResponse(
            items=items_breakdown,
            # Subtotal is sum of item prices without taxes
            subtotal=round(subtotal, 2),
            total_tax_amount=round(total_tax_amount, 2),
            total_amount=round(total_amount_with_taxes, 2),
            discount_amount=round(discount_amount, 2),
            final_amount=round(final_amount, 2),
            voucher_code=voucher_code,
            voucher_valid=voucher_valid,
            store_state=store_state
        )

    async def update_order(
        self,
        user_id: int,
        order_id: int,
        data: OrderUpdateRequest
    ) -> OrderResponse:
        order = await self._load_order_for_user(user_id, order_id)

        if order.status != OrderStatusEnum.IN_PROCESS:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Only orders in process can be updated"
            )

        if not order.items:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order has no items to update"
            )

        existing_items = {item.listing_id: item for item in order.items}
        update_map: dict[int, int] = {}

        # Build update map from request
        # Items not in the request will be removed (unless they're already in the order and not mentioned)
        for item in data.items:
            if item.listing_id not in existing_items:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Listing {item.listing_id} is not part of this order"
                )
            if item.listing_id in update_map:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Duplicate listing provided: {item.listing_id}"
                )
            if item.quantity < 0:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Quantity cannot be negative for listing {item.listing_id}"
                )
            update_map[item.listing_id] = item.quantity

        # Items not in update_map will be removed
        # Check if at least one item will remain
        remaining_count = sum(
            1 for listing_id in existing_items
            if listing_id in update_map and update_map[listing_id] > 0
        )
        if remaining_count == 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order must contain at least one item with quantity > 0"
            )
        
        total_amount = 0.0
        total_tax_amount = 0.0
        items_to_delete: List[UserOrderItem] = []
        
        # Get store_id from order
        store_id = order.store_id
        # Get store's state for tax calculation
        store_state = await self._get_store_state(store_id) if store_id else None

        # Process all existing order items
        # First, ensure all listings are properly loaded with all relationships
        listing_ids_to_reload = []
        for order_item in order.items:
            listing = getattr(order_item, 'listing', None)
            if listing is None:
                listing_ids_to_reload.append(order_item.listing_id)
            else:
                # Check if product is loaded
                product = getattr(listing, 'product', None)
                if product is None:
                    listing_ids_to_reload.append(order_item.listing_id)
        
        # Reload all listings that need to be loaded
        if listing_ids_to_reload:
            stmt = (
                select(ProductListing)
                .options(
                    selectinload(ProductListing.product)
                    .selectinload(Product.category)
                    .selectinload(ProductCategory.taxes),
                    selectinload(ProductListing.product)
                    .selectinload(Product.taxes),
                    selectinload(ProductListing.store),
                )
                .where(ProductListing.listing_id.in_(listing_ids_to_reload))
            )
            result = await self.db.execute(stmt)
            reloaded_listings = {listing.listing_id: listing for listing in result.scalars().all()}
            
            # Assign reloaded listings to order items
            for order_item in order.items:
                if order_item.listing_id in reloaded_listings:
                    order_item.listing = reloaded_listings[order_item.listing_id]
        
        # Now process all items
        for order_item in order.items:
            listing = getattr(order_item, 'listing', None)
            
            if listing is None:
                # If listing doesn't exist, mark item for deletion
                items_to_delete.append(order_item)
                continue

            # Check if this item should be removed (not in update_map or quantity is 0)
            if order_item.listing_id not in update_map or update_map[order_item.listing_id] == 0:
                items_to_delete.append(order_item)
                continue

            # Update quantity and recalculate pricing
            new_quantity = update_map[order_item.listing_id]
            order_item.quantity = new_quantity
            
            # Recalculate unit price (may have changed due to discounts)
            unit_price = self._calculate_unit_price(listing)
            order_item.unit_price = unit_price
            order_item.total_price = round(unit_price * order_item.quantity, 2)
            total_amount += order_item.total_price
            
            # Calculate taxes for this item based on store's state
            tax_amount = self._calculate_taxes(listing, unit_price, order_item.quantity, store_state)
            total_tax_amount += tax_amount

        # Delete items that should be removed
        for order_item in items_to_delete:
            self.db.delete(order_item)

        # Calculate total amount with taxes
        total_amount_with_taxes = total_amount + total_tax_amount

        discount_amount = 0.0
        if order.voucher:
            voucher = order.voucher
            if not voucher.is_active:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Voucher is no longer active"
                )
            if not self.voucher_service._is_voucher_valid_today(voucher):
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Voucher is not valid on the current date"
                )
            if voucher.min_order_amount and total_amount_with_taxes < voucher.min_order_amount:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Minimum order amount to use this voucher is {voucher.min_order_amount}"
                )
            discount_amount = self.voucher_service._calculate_discount(voucher, total_amount_with_taxes)

        # Calculate final amount (total with taxes minus discount)
        final_amount = max(total_amount_with_taxes - discount_amount, 0.0)

        if order.payment_intent_id:
            await self._cancel_payment_intent(order.payment_intent_id)
            order.payment_intent_id = None

        order.total_amount = total_amount_with_taxes
        order.discount_amount = discount_amount
        order.final_amount = final_amount
        order.payment_status = "PENDING"

        await self.db.commit()

        # Reload order with all relationships to avoid lazy loading issues
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store)
                .selectinload(Store.chain),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store)
                .selectinload(Store.chain),
            )
            .where(UserOrder.order_id == order_id)
        )
        result = await self.db.execute(stmt)
        reloaded_order = result.scalar_one_or_none()
        
        if not reloaded_order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found after update"
            )

        return self._build_order_response(reloaded_order)

    async def create_payment_intent(
        self,
        user_id: int,
        order_id: int,
        chain_code: str
    ) -> OrderPaymentIntentResponse:
        order = await self._load_order_for_user(user_id, order_id)

        if order.status != OrderStatusEnum.IN_PROCESS:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Only orders in process can create payment intents"
            )

        # Validate chain_code - get chain from order items
        if not order.items:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order has no items"
            )

        # Get chain from the first item's listing store
        # All items should be from the same chain, but we'll check the first one
        first_item = order.items[0]
        if not first_item.listing or not first_item.listing.store:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order item does not have a valid store"
            )

        store = first_item.listing.store
        if not store.chain:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Store does not have a valid chain"
            )

        # Validate chain_code matches
        if store.chain.chain_code != chain_code:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Chain code is incorrect"
            )

        amount_cents = self._amount_to_cents(order.final_amount)
        if amount_cents <= 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order total must be greater than zero to create a payment intent"
            )

        self._ensure_stripe_configured()
        currency = self._get_stripe_currency()

        if order.payment_intent_id:
            await self._cancel_payment_intent(order.payment_intent_id)

        try:
            payment_intent = stripe.PaymentIntent.create(
                amount=amount_cents,
                currency=currency,
                metadata={
                    "order_id": order.order_id,
                    "user_id": user_id,
                },
                automatic_payment_methods={"enabled": True},
            )
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error: {exc.user_message or str(exc)}"
            )

        order.payment_intent_id = payment_intent.id
        order.payment_status = payment_intent.status.upper()

        await self.db.commit()
        await self.db.refresh(order, attribute_names=["items", "voucher"])

        client_secret = payment_intent.client_secret
        if not client_secret:
            try:
                refreshed_intent = stripe.PaymentIntent.retrieve(payment_intent.id)
                client_secret = refreshed_intent.client_secret
            except stripe.error.StripeError as exc:
                raise HTTPException(
                    status_code=status.HTTP_502_BAD_GATEWAY,
                    detail=f"Stripe error: {exc.user_message or str(exc)}"
                )
        if not client_secret:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Unable to retrieve Stripe payment intent client secret"
            )

        return OrderPaymentIntentResponse(
            payment_intent_id=payment_intent.id,
            client_secret=client_secret,
            amount=payment_intent.amount,
            currency=payment_intent.currency,
            status=payment_intent.status,
        )

    async def confirm_payment(
        self,
        user_id: int,
        order_id: int,
        payload: OrderPaymentConfirmRequest
    ) -> OrderResponse:
        order = await self._load_order_for_user(user_id, order_id)

        if order.payment_intent_id != payload.payment_intent_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Payment intent does not match this order"
            )

        self._ensure_stripe_configured()

        try:
            payment_intent = stripe.PaymentIntent.retrieve(payload.payment_intent_id)
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error: {exc.user_message or str(exc)}"
            )

        order.payment_status = payment_intent.status.upper()

        if payment_intent.status == "succeeded":
            order.status = OrderStatusEnum.COMPLETED
            if payment_intent.amount_received:
                amount_received = Decimal(payment_intent.amount_received) / Decimal("100")
                order.final_amount = float(amount_received)
            
            # Create transaction for chain wallet
            # Get chain_id from order's store
            if order.store and order.store.chain_id:
                try:
                    from app.services.staff.transaction_service import TransactionService
                    transaction_service = TransactionService(self.db)
                    await transaction_service.create_sale_transaction(
                        chain_id=order.store.chain_id,
                        order_id=order.order_id,
                        gross_amount=order.final_amount,
                        stripe_payment_intent_id=payment_intent.id
                    )
                except Exception as e:
                    # Log error but don't fail the payment confirmation
                    # Transaction creation can be retried later if needed
                    print(f"Warning: Failed to create transaction for order {order_id}: {str(e)}")
        else:
            await self.db.commit()
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Payment intent status is {payment_intent.status}"
            )

        await self.db.commit()

        # Reload order with all relationships to avoid lazy loading issues
        order = await self._load_order_for_user(user_id, order_id)

        return self._build_order_response(order)

    async def refund_order(
        self,
        order_id: int,
        refund_request: Optional[OrderRefundRequest] = None
    ) -> OrderRefundResponse:
        """
        Refund an order via Stripe. Only accessible by admin.
        Refunds the full amount (including taxes) back to the user's card.
        """
        # Load order with all relationships
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store)
                .selectinload(Store.chain),
            )
            .where(UserOrder.order_id == order_id)
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()

        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )

        # Check if order is already refunded
        if order.status == OrderStatusEnum.REFUNDED:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order has already been refunded"
            )

        # Check if order has a payment intent
        if not order.payment_intent_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order does not have a payment intent. Cannot refund unpaid order."
            )

        # Check if payment was successful
        if order.payment_status.upper() != "SUCCEEDED":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot refund order with payment status: {order.payment_status}"
            )

        self._ensure_stripe_configured()

        try:
            # Retrieve the payment intent to get the charge ID
            payment_intent = stripe.PaymentIntent.retrieve(order.payment_intent_id)
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error retrieving payment intent: {exc.user_message or str(exc)}"
            )

        # Get the charge ID from the payment intent
        if not payment_intent.latest_charge:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Payment intent does not have a charge. Cannot process refund."
            )

        # latest_charge can be a string (charge ID) or a Charge object
        charge_id = payment_intent.latest_charge
        if hasattr(charge_id, 'id'):
            # If it's a Charge object, get the ID
            charge_id = charge_id.id
        # Otherwise, it's already a string charge ID

        # Calculate refund amount in cents (full amount including taxes)
        refund_amount_cents = self._amount_to_cents(order.final_amount)

        if refund_amount_cents <= 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Order amount is zero or negative. Cannot process refund."
            )

        try:
            # Create refund via Stripe
            # Stripe will automatically refund the full amount including any fees
            refund = stripe.Refund.create(
                charge=charge_id,
                amount=refund_amount_cents,
                reason="requested_by_customer" if refund_request and refund_request.reason else None,
                metadata={
                    "order_id": order.order_id,
                    "user_id": order.user_id,
                    "refund_reason": refund_request.reason if refund_request and refund_request.reason else "Admin refund",
                }
            )
        except stripe.error.StripeError as exc:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Stripe error creating refund: {exc.user_message or str(exc)}"
            )

        # Calculate refund amount in dollars
        refund_amount_dollars = Decimal(refund.amount) / Decimal("100")
        
        # Update order status
        order.status = OrderStatusEnum.REFUNDED
        order.payment_status = "REFUNDED"

        # Create refund transaction for chain wallet
        # Get chain_id from order's store
        if order.store and order.store.chain_id:
            try:
                from app.services.staff.transaction_service import TransactionService
                transaction_service = TransactionService(self.db)
                await transaction_service.create_refund_transaction(
                    chain_id=order.store.chain_id,
                    order_id=order.order_id,
                    refund_amount=float(refund_amount_dollars)
                )
            except Exception as e:
                # Log error but don't fail the refund
                # Transaction creation can be retried later if needed
                import traceback
                print(f"Warning: Failed to create refund transaction for order {order_id}: {str(e)}")
                print(traceback.format_exc())

        await self.db.commit()
        await self.db.refresh(order)

        return OrderRefundResponse(
            order_id=order.order_id,
            status=OrderStatusEnum.REFUNDED,
            refund_id=refund.id,
            refund_amount=float(refund_amount_dollars),
            refund_amount_cents=refund.amount,
            message=f"Order {order.order_id} has been successfully refunded. Amount: ${refund_amount_dollars:.2f}"
        )

    async def get_user_orders(
        self,
        user_id: int,
        status_filter: Optional[OrderStatusEnum] = None
    ) -> List[OrderResponse]:
        await self._ensure_user_exists(user_id)

        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .where(UserOrder.user_id == user_id)
            .order_by(UserOrder.created_at.desc())
        )
        if status_filter:
            stmt = stmt.where(UserOrder.status == status_filter)

        result = await self.db.execute(stmt)
        orders = result.scalars().all()
        return [self._build_order_response(order) for order in orders]

    async def cancel_order(self, user_id: int, order_id: int) -> OrderCancelResponse:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.voucher),
            )
            .where(
                UserOrder.order_id == order_id,
                UserOrder.user_id == user_id,
            )
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()

        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )

        if order.status != OrderStatusEnum.IN_PROCESS:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Only orders in process can be cancelled"
            )

        if order.payment_intent_id and order.payment_status.upper() != "SUCCEEDED":
            await self._cancel_payment_intent(order.payment_intent_id)
            order.payment_intent_id = None
            order.payment_status = "CANCELLED"

        order.status = OrderStatusEnum.CANCELLED
        if order.payment_status.upper() != "SUCCEEDED":
            order.payment_status = "CANCELLED"
        await self.db.commit()
        await self.db.refresh(order)

        if order.voucher:
            await self.voucher_service.decrement_usage(order.voucher)

        return OrderCancelResponse(
            order_id=order.order_id,
            status=order.status,
            message="Order has been cancelled successfully",
        )

    async def get_chain_orders(
        self,
        chain_id: int,
        status_filter: Optional[OrderStatusEnum] = None,
        skip: int = 0,
        limit: int = 100
    ) -> List[OrderResponse]:
        """
        Get all orders for stores in a specific chain.
        """
        # Get store IDs for this chain
        from app.models.staff.store_model import Store
        store_ids_stmt = select(Store.store_id).where(Store.chain_id == chain_id)
        store_ids_result = await self.db.execute(store_ids_stmt)
        store_ids = [row[0] for row in store_ids_result.all()]

        if not store_ids:
            return []

        # Build query for orders from these stores
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .where(UserOrder.store_id.in_(store_ids))
            .order_by(UserOrder.created_at.desc())
        )

        if status_filter:
            stmt = stmt.where(UserOrder.status == status_filter)

        # Apply pagination
        stmt = stmt.offset(skip).limit(limit)

        result = await self.db.execute(stmt)
        orders = result.scalars().all()
        return [self._build_order_response(order) for order in orders]

    async def list_orders(
        self,
        status_filter: Optional[OrderStatusEnum] = None
    ) -> List[OrderResponse]:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .order_by(UserOrder.created_at.desc())
        )
        if status_filter:
            stmt = stmt.where(UserOrder.status == status_filter)

        result = await self.db.execute(stmt)
        orders = result.scalars().all()
        return [self._build_order_response(order) for order in orders]

    async def get_order(self, order_id: int) -> OrderResponse:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .where(UserOrder.order_id == order_id)
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()

        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )

        return self._build_order_response(order)

    async def get_order_for_user(self, user_id: int, order_id: int) -> OrderResponse:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.category)
                .selectinload(ProductCategory.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.product)
                .selectinload(Product.taxes),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .where(
                UserOrder.order_id == order_id,
                UserOrder.user_id == user_id,
            )
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()

        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )

        return self._build_order_response(order)

    async def update_order_status(self, order_id: int, status_update: OrderStatusEnum) -> OrderResponse:
        stmt = (
            select(UserOrder)
            .options(
                selectinload(UserOrder.items).selectinload(UserOrderItem.product),
                selectinload(UserOrder.items)
                .selectinload(UserOrderItem.listing)
                .selectinload(ProductListing.store),
                selectinload(UserOrder.voucher),
                selectinload(UserOrder.store),
            )
            .where(UserOrder.order_id == order_id)
        )
        result = await self.db.execute(stmt)
        order = result.scalar_one_or_none()

        if not order:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Order not found"
            )

        if order.status == OrderStatusEnum.CANCELLED and status_update == OrderStatusEnum.COMPLETED:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Cancelled orders cannot be marked as completed"
            )

        order.status = status_update
        await self.db.commit()
        await self.db.refresh(order)

        return self._build_order_response(order)

