"""
Customer service for browsing products, stores, and categories
"""
from typing import List, Optional
from datetime import date
from math import radians, sin, cos, sqrt, atan2
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_
from sqlalchemy.orm import selectinload
from fastapi import HTTPException, status

from app.models.listing.products import Product, ProductCategory, ProductListing, ChainProduct
from app.models.staff.store_model import Store
from app.models.user.user_model import User
from app.enums.enums import ListingStatusEnum, ListingTypeEnum, ProductStatusEnum


def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """
    Calculate the distance between two points on Earth using Haversine formula.
    Returns distance in kilometers.
    """
    # Earth radius in kilometers
    R = 6371.0
    
    # Convert latitude and longitude from degrees to radians
    lat1_rad = radians(lat1)
    lon1_rad = radians(lon1)
    lat2_rad = radians(lat2)
    lon2_rad = radians(lon2)
    
    # Differences in coordinates
    dlat = lat2_rad - lat1_rad
    dlon = lon2_rad - lon1_rad
    
    # Haversine formula
    a = sin(dlat / 2) ** 2 + cos(lat1_rad) * cos(lat2_rad) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    
    # Distance in kilometers
    distance = R * c
    return distance


class CustomerService:
    def __init__(self, db: AsyncSession):
        self.db = db
    
    async def _get_user_state(self, user_id: Optional[int] = None) -> Optional[str]:
        """Get the user's state from their active address. Returns state code (e.g., 'CA', 'NY') or None."""
        if not user_id:
            return None
        
        from app.models.user.user_model import UserAddress
        stmt = select(UserAddress).where(
            UserAddress.user_id == user_id,
            UserAddress.is_active == True
        ).order_by(UserAddress.created_at.desc())
        result = await self.db.execute(stmt)
        active_address = result.scalar_one_or_none()
        
        if active_address and active_address.state:
            return active_address.state.upper().strip()
        return None
    
    # Removed _get_category_taxes_for_state - taxes are now only loaded when needed in order/pricing APIs
    
    async def get_stores_by_category(
        self,
        category_id: int,
        chain_id: Optional[int] = None,
        skip: int = 0,
        limit: int = 100
    ) -> dict:
        """
        Return stores that currently have at least one APPROVED listing live (UTC) for products in the given category.
        """
        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()

        # Build query to find distinct stores with live listings for the category
        stmt = (
            select(Store)
            .join(ProductListing, ProductListing.store_id == Store.store_id)
            .join(Product, Product.product_id == ProductListing.product_id)
            .where(
                and_(
                    Product.category_id == category_id,
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date <= today_utc,
                )
            )
            .distinct()
            .order_by(Store.store_name)
        )
        if chain_id:
            stmt = stmt.where(Store.chain_id == chain_id)

        # Total count
        from sqlalchemy import func as sql_func
        count_stmt = (
            select(sql_func.count())
            .select_from(
                select(Store.store_id)
                .join(ProductListing, ProductListing.store_id == Store.store_id)
                .join(Product, Product.product_id == ProductListing.product_id)
                .where(
                    and_(
                        Product.category_id == category_id,
                        Product.status == ProductStatusEnum.APPROVED,
                        Product.is_deleted == False,  # Exclude soft-deleted products
                        ProductListing.status == ListingStatusEnum.APPROVED,
                        ProductListing.go_live_date <= today_utc,
                        *( [Store.chain_id == chain_id] if chain_id else [] )
                    )
                )
                .distinct()
                .subquery()
            )
        )

        count_result = await self.db.execute(count_stmt)
        total = count_result.scalar() or 0

        # Pagination
        stmt = stmt.offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        stores = result.scalars().all()

        stores_list = [
            {
                "store_id": s.store_id,
                "store_name": s.store_name,
                "store_location": s.store_location,
                "store_operational_hours": s.store_operational_hours,
                "chain_id": s.chain_id,
                "latitude": s.latitude,
                "longitude": s.longitude,
                "created_at": s.created_at,
                "updated_at": s.updated_at,
            }
            for s in stores
        ]

        return {
            "stores": stores_list,
            "total": total,
            "skip": skip,
            "limit": limit,
        }
    async def get_all_categories(self, chain_id: Optional[int] = None) -> List[dict]:
        """Get all product categories, optionally filtered by chain"""
        stmt = select(ProductCategory).options(selectinload(ProductCategory.products))

        if chain_id:
            stmt = (
                stmt.join(Product, Product.category_id == ProductCategory.category_id)
                .join(ChainProduct, ChainProduct.product_id == Product.product_id)
                .where(
                    and_(
                        ChainProduct.chain_id == chain_id,
                        Product.status == ProductStatusEnum.APPROVED,
                        Product.is_deleted == False,  # Exclude soft-deleted products
                    )
                )
                .distinct()
            )

        stmt = stmt.order_by(ProductCategory.category_name)

        result = await self.db.execute(stmt)
        categories = result.scalars().all()

        return [
            {
                "category_id": cat.category_id,
                "category_name": cat.category_name,
                "category_image_link": cat.category_image_link,
                "product_count": len(cat.products) if hasattr(cat, "products") else 0,
                # Taxes not included in general category listing - only loaded when needed for order/pricing
                "created_at": cat.created_at,
                "updated_at": cat.updated_at,
            }
            for cat in categories
        ]
    
    async def get_all_stores(
        self,
        chain_id: Optional[int] = None,
        search: Optional[str] = None,
        skip: int = 0,
        limit: int = 100
    ) -> dict:
        """Get all stores with pagination"""
        # Build query
        stmt = select(Store)
        
        # Apply filters
        conditions = []
        if chain_id:
            conditions.append(Store.chain_id == chain_id)
        
        if search:
            conditions.append(
                or_(
                    Store.store_name.ilike(f"%{search}%"),
                    Store.store_location.ilike(f"%{search}%")
                )
            )
        
        if conditions:
            stmt = stmt.where(and_(*conditions))
        
        # Get total count
        from sqlalchemy import func as sql_func
        count_stmt = select(sql_func.count()).select_from(Store)
        if conditions:
            count_stmt = count_stmt.where(and_(*conditions))
        
        count_result = await self.db.execute(count_stmt)
        total_count = count_result.scalar()
        
        # Get stores with pagination
        stmt = stmt.order_by(Store.store_name).offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        stores = result.scalars().all()
        
        stores_list = [
            {
                "store_id": store.store_id,
                "store_name": store.store_name,
                "store_location": store.store_location,
                "store_operational_hours": store.store_operational_hours,
                "chain_id": store.chain_id,
                "latitude": store.latitude,
                "longitude": store.longitude,
                "created_at": store.created_at,
                "updated_at": store.updated_at
            }
            for store in stores
        ]
        
        return {
            "stores": stores_list,
            "total": total_count,
            "skip": skip,
            "limit": limit
        }
    
    async def get_nearby_stores(
        self,
        user_id: int,
        radius_km: float = 1.0,
        chain_id: Optional[int] = None,
        limit: int = 100
    ) -> dict:
        """
        Get stores within a specified radius from user's location.
        Only returns stores with valid latitude/longitude and user with valid location.
        """
        # Get user to get their location
        user_stmt = select(User).where(User.user_id == user_id)
        user_result = await self.db.execute(user_stmt)
        user = user_result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="User not found"
            )
        
        # Check if user has location data
        if user.latitude is None or user.longitude is None:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User location not set. Please update your profile with latitude and longitude."
            )
        
        # Get all stores (we'll filter by distance in Python since we need haversine)
        stmt = select(Store).where(
            Store.latitude.isnot(None),
            Store.longitude.isnot(None)
        )
        
        if chain_id:
            stmt = stmt.where(Store.chain_id == chain_id)
        
        result = await self.db.execute(stmt)
        all_stores = result.scalars().all()
        
        # Calculate distance for each store and filter by radius
        nearby_stores = []
        for store in all_stores:
            distance = haversine_distance(
                user.latitude, user.longitude,
                store.latitude, store.longitude
            )
            
            if distance <= radius_km:
                nearby_stores.append({
                    "store_id": store.store_id,
                    "store_name": store.store_name,
                    "store_location": store.store_location,
                    "store_operational_hours": store.store_operational_hours,
                    "chain_id": store.chain_id,
                    "latitude": store.latitude,
                    "longitude": store.longitude,
                    "distance_km": round(distance, 2),
                    "created_at": store.created_at,
                    "updated_at": store.updated_at
                })
        
        # Sort by distance (closest first) and apply limit
        nearby_stores.sort(key=lambda x: x["distance_km"])
        nearby_stores = nearby_stores[:limit]
        
        return {
            "stores": nearby_stores,
            "total": len(nearby_stores),
            "radius_km": radius_km,
            "user_location": {
                "latitude": user.latitude,
                "longitude": user.longitude
            }
        }
    
    async def get_store_live_products(
        self,
        store_id: int,
        category_id: Optional[int] = None,
        search: Optional[str] = None,
        listing_type_filter: Optional[ListingTypeEnum] = None,
        skip: int = 0,
        limit: int = 100
    ) -> dict:
        """Get approved products for a specific store"""
        # Get store
        store_stmt = select(Store).where(Store.store_id == store_id)
        store_result = await self.db.execute(store_stmt)
        store = store_result.scalar_one_or_none()
        
        if not store:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Store not found"
            )
        
        # Get approved listings only
        # Use UTC date for comparison (go_live_date is stored in UTC)
        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()
        
        # Build base query - must join Product to check approval status
        # Exclude expired BEST_BY_PRODUCTS (where best_by_date has passed)
        listing_stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.product).selectinload(Product.category)
            )
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    ProductListing.store_id == store_id,
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date <= today_utc,
                    Product.status == ProductStatusEnum.APPROVED,  # Product must be approved
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    # Exclude expired BEST_BY_PRODUCTS: either not BEST_BY_PRODUCTS type, or best_by_date is null, or best_by_date >= today
                    or_(
                        ProductListing.listing_type != ListingTypeEnum.BEST_BY_PRODUCTS,
                        ProductListing.best_by_date.is_(None),
                        ProductListing.best_by_date >= today_utc
                    )
                )
            )
        )
        if listing_type_filter:
            listing_stmt = listing_stmt.where(ProductListing.listing_type == listing_type_filter)
        
        # Apply filters
        if category_id:
            listing_stmt = listing_stmt.where(Product.category_id == category_id)
        
        if search:
            listing_stmt = listing_stmt.where(
                Product.product_name.ilike(f"%{search}%")
            )
        
        # Get total count (before pagination)
        from sqlalchemy import func as sql_func
        count_stmt = (
            select(sql_func.count())
            .select_from(ProductListing)
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    ProductListing.store_id == store_id,
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date <= today_utc,
                    Product.status == ProductStatusEnum.APPROVED,  # Product must be approved
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    # Exclude expired BEST_BY_PRODUCTS: either not BEST_BY_PRODUCTS type, or best_by_date is null, or best_by_date >= today
                    or_(
                        ProductListing.listing_type != ListingTypeEnum.BEST_BY_PRODUCTS,
                        ProductListing.best_by_date.is_(None),
                        ProductListing.best_by_date >= today_utc
                    )
                )
            )
        )
        if listing_type_filter:
            count_stmt = count_stmt.where(ProductListing.listing_type == listing_type_filter)
        if category_id:
            count_stmt = count_stmt.where(Product.category_id == category_id)
        if search:
            count_stmt = count_stmt.where(Product.product_name.ilike(f"%{search}%"))
        
        count_result = await self.db.execute(count_stmt)
        total_count = count_result.scalar()
        
        # Apply pagination
        listing_stmt = listing_stmt.offset(skip).limit(limit)
        listing_result = await self.db.execute(listing_stmt)
        listings = listing_result.scalars().all()
        
        products = []
        for listing in listings:
            discounted_info = self._calculate_current_discount(listing)
            
            products.append({
                "listing_id": listing.listing_id,
                "product_id": listing.product.product_id,
                "product_name": listing.product.product_name,
                "product_description": listing.product.product_description,
                "product_image": listing.product.product_image,
                "product_barcode": listing.product.product_barcode,
                "unit": listing.product.unit,
                "base_price": listing.product.base_price,
                "category": {
                    "category_id": listing.product.category.category_id,
                    "category_name": listing.product.category.category_name,
                    "category_image_link": listing.product.category.category_image_link,
                    # Taxes not included in general product listing - only loaded when needed for order/pricing
                } if listing.product.category else None,
                "listing_type": listing.listing_type,
                "quantity": listing.quantity,
                "best_by_date": listing.best_by_date,
                "go_live_date": listing.go_live_date,
                "status": listing.status,
                "current_discount_percent": discounted_info["current_discount_percent"],
                "discounted_price": discounted_info["discounted_price"],
                "days_until_expiry": discounted_info.get("days_until_expiry"),
                "average_price": listing.average_price,
            })
        
        return {
            "store": {
                "store_id": store.store_id,
                "store_name": store.store_name,
                "store_location": store.store_location,
                "store_operational_hours": store.store_operational_hours,
                "chain_id": store.chain_id
            },
            "products": products,
            "total": total_count,
            "skip": skip,
            "limit": limit
        }
    
    async def get_product_details(
        self,
        product_id: int,
        store_id: Optional[int] = None
    ) -> dict:
        """Get detailed product information"""
        # Get product
        stmt = select(Product).options(
            selectinload(Product.category)
        ).where(
            and_(
                Product.product_id == product_id,
                Product.is_deleted == False  # Exclude soft-deleted products
            )
        )
        
        result = await self.db.execute(stmt)
        product = result.scalar_one_or_none()
        
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        
        product_data = {
            "product_id": product.product_id,
            "product_name": product.product_name,
            "product_description": product.product_description,
            "product_image": product.product_image,
            "product_barcode": product.product_barcode,
            "unit": product.unit,
            "base_price": product.base_price,
            "category": {
                "category_id": product.category.category_id,
                "category_name": product.category.category_name,
                "category_image_link": product.category.category_image_link,
                # Taxes not included in general product listing - only loaded when needed for order/pricing
            } if product.category else None,
            "created_at": product.created_at,
            "updated_at": product.updated_at
        }
        
        # If store_id provided, get listing info for that store
        if store_id:
            # Use UTC date for comparison (go_live_date is stored in UTC)
            from datetime import timezone
            from datetime import datetime as dt
            today_utc = dt.now(timezone.utc).date()
            # Join with Product to filter out soft-deleted products
            listing_stmt = (
                select(ProductListing)
                .join(Product, ProductListing.product_id == Product.product_id)
                .where(
                    and_(
                        ProductListing.product_id == product_id,
                        ProductListing.store_id == store_id,
                        ProductListing.status == ListingStatusEnum.APPROVED,  # Only APPROVED status
                        ProductListing.go_live_date <= today_utc,
                        Product.is_deleted == False  # Exclude soft-deleted products
                    )
                )
            )
            
            listing_result = await self.db.execute(listing_stmt)
            listing = listing_result.scalar_one_or_none()
            
            if listing:
                discounted_info = self._calculate_current_discount(listing)
                product_data["store_availability"] = {
                    "store_id": store_id,
                    "available": True,
                    "listing_id": listing.listing_id,
                    "quantity": listing.quantity,
                    "listing_type": listing.listing_type,
                    "current_discount_percent": discounted_info["current_discount_percent"],
                    "discounted_price": discounted_info["discounted_price"],
                    "days_until_expiry": discounted_info.get("days_until_expiry"),
                    "best_by_date": listing.best_by_date
                }
            else:
                product_data["store_availability"] = {
                    "store_id": store_id,
                    "available": False
                }
        
        return product_data
    
    async def get_product_by_barcode(
        self,
        barcode: str,
        store_id: Optional[int] = None
    ) -> dict:
        """Get product details by barcode - only returns approved products"""
        # Get product by barcode - must be approved
        stmt = (
            select(Product)
            .options(selectinload(Product.category))
            .where(
                and_(
                    Product.product_barcode == barcode,
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        
        result = await self.db.execute(stmt)
        product = result.scalar_one_or_none()
        
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found or not approved"
            )
        
        product_data = {
            "product_id": product.product_id,
            "product_name": product.product_name,
            "product_description": product.product_description,
            "product_image": product.product_image,
            "product_barcode": product.product_barcode,
            "unit": product.unit,
            "base_price": product.base_price,
            "category": {
                "category_id": product.category.category_id,
                "category_name": product.category.category_name,
                "category_image_link": product.category.category_image_link,
                # Taxes not included in general product listing - only loaded when needed for order/pricing
            } if product.category else None,
            "created_at": product.created_at,
            "updated_at": product.updated_at
        }
        
        # Get all approved listings for this product
        # Use UTC date for comparison (go_live_date is stored in UTC)
        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()
        listing_stmt = (
            select(ProductListing)
            .options(selectinload(ProductListing.store))
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    ProductListing.product_id == product.product_id,
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date <= today_utc,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        
        if store_id:
            listing_stmt = listing_stmt.where(ProductListing.store_id == store_id)
        
        listing_result = await self.db.execute(listing_stmt)
        listings = listing_result.scalars().all()
        
        # Build store availability list
        store_availability = []
        for listing in listings:
            discounted_info = self._calculate_current_discount(listing)
            store_availability.append({
                "store_id": listing.store.store_id,
                "store_name": listing.store.store_name,
                "store_location": listing.store.store_location,
                "store_operational_hours": listing.store.store_operational_hours,
                "chain_id": listing.store.chain_id,
                "available": True,
                "listing_id": listing.listing_id,
                "quantity": listing.quantity,
                "listing_type": listing.listing_type,
                "current_discount_percent": discounted_info["current_discount_percent"],
                "discounted_price": discounted_info["discounted_price"],
                "days_until_expiry": discounted_info.get("days_until_expiry"),
                "best_by_date": listing.best_by_date,
                "go_live_date": listing.go_live_date
            })
        
        product_data["store_availability"] = store_availability
        
        return product_data
    
    async def get_all_approved_products(
        self,
        category_id: Optional[int] = None,
        search: Optional[str] = None,
        skip: int = 0,
        limit: int = 100
    ) -> dict:
        """Get all approved products (regardless of listing status) with pagination and search"""
        # Build base query - get all approved products (not filtered by listings)
        product_stmt = (
            select(Product)
            .options(selectinload(Product.category))
            .where(
                and_(
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        
        # Apply filters
        if category_id:
            product_stmt = product_stmt.where(Product.category_id == category_id)
        
        if search:
            search_term = f"%{search.lower()}%"
            product_stmt = product_stmt.where(
                or_(
                    Product.product_name.ilike(search_term),
                    Product.product_description.ilike(search_term),
                    Product.product_barcode.ilike(search_term)
                )
            )
        
        # Get total count (before pagination)
        from sqlalchemy import func as sql_func
        count_stmt = (
            select(sql_func.count(Product.product_id))
            .where(
                and_(
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        if category_id:
            count_stmt = count_stmt.where(Product.category_id == category_id)
        if search:
            search_term = f"%{search.lower()}%"
            count_stmt = count_stmt.where(
                or_(
                    Product.product_name.ilike(search_term),
                    Product.product_description.ilike(search_term),
                    Product.product_barcode.ilike(search_term)
                )
            )
        
        count_result = await self.db.execute(count_stmt)
        total_count = count_result.scalar()
        
        # Apply pagination
        product_stmt = product_stmt.order_by(Product.created_at.desc()).offset(skip).limit(limit)
        product_result = await self.db.execute(product_stmt)
        products_list = product_result.scalars().all()
        
        # Get all active listings for these products to attach listing info
        # Use UTC date for comparison (go_live_date is stored in UTC)
        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()
        product_ids = [p.product_id for p in products_list]
        listing_stmt = (
            select(ProductListing)
            .options(selectinload(ProductListing.store))
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    ProductListing.product_id.in_(product_ids),
                    ProductListing.status == ListingStatusEnum.APPROVED,
                    ProductListing.go_live_date <= today_utc,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        listing_result = await self.db.execute(listing_stmt)
        listings = listing_result.scalars().all()
        
        # Create a map of product_id -> listings
        listings_by_product = {}
        for listing in listings:
            if listing.product_id not in listings_by_product:
                listings_by_product[listing.product_id] = []
            listings_by_product[listing.product_id].append(listing)
        
        products = []
        for product in products_list:
            # Get the first active listing if available (or None)
            active_listings = listings_by_product.get(product.product_id, [])
            listing = active_listings[0] if active_listings else None
            
            # Build product data
            product_data = {
                "product_id": product.product_id,
                "product_name": product.product_name,
                "product_description": product.product_description,
                "product_image": product.product_image,
                "product_barcode": product.product_barcode,
                "unit": product.unit,
                "base_price": product.base_price,
                "category": {
                    "category_id": product.category.category_id,
                    "category_name": product.category.category_name,
                    "category_image_link": product.category.category_image_link,
                    # Taxes not included in general product listing - only loaded when needed for order/pricing
                } if product.category else None,
            }
            
            # Add listing info if available
            if listing:
                discounted_info = self._calculate_current_discount(listing)
                product_data.update({
                    "listing_id": listing.listing_id,
                    "listing_type": listing.listing_type,
                    "quantity": listing.quantity,
                    "best_by_date": listing.best_by_date,
                    "go_live_date": listing.go_live_date,
                    "status": listing.status,
                    "current_discount_percent": discounted_info["current_discount_percent"],
                    "discounted_price": discounted_info["discounted_price"],
                    "days_until_expiry": discounted_info.get("days_until_expiry"),
                    "average_price": listing.average_price,
                    "store": {
                        "store_id": listing.store.store_id,
                        "store_name": listing.store.store_name,
                        "store_location": listing.store.store_location,
                        "store_operational_hours": listing.store.store_operational_hours,
                        "chain_id": listing.store.chain_id
                    } if listing.store else None
                })
            else:
                # No active listing
                product_data.update({
                    "listing_id": None,
                    "listing_type": None,
                    "quantity": None,
                    "best_by_date": None,
                    "go_live_date": None,
                    "status": None,
                    "current_discount_percent": 0.0,
                    "discounted_price": product.base_price,
                    "days_until_expiry": None,
                    "average_price": None,
                    "store": None
                })
            
            products.append(product_data)
        
        return {
            "products": products,
            "total": total_count,
            "skip": skip,
            "limit": limit
        }
    
    def _calculate_current_discount(self, listing: ProductListing) -> dict:
        """Calculate current discount and price for a listing"""
        if not listing.current_discount or not listing.daily_increasing_discount_percent:
            return {
                "current_discount_percent": 0.0,
                "discounted_price": listing.product.base_price,
                "days_until_expiry": None
            }
        
        # Calculate days since go_live_date (use UTC for consistency)
        from datetime import timezone
        from datetime import datetime as dt
        today_utc = dt.now(timezone.utc).date()
        days_passed = (today_utc - listing.go_live_date).days if listing.go_live_date else 0
        
        # Calculate total discount
        total_discount = listing.current_discount + (listing.daily_increasing_discount_percent * days_passed)
        total_discount = min(total_discount, 80.0)  # Cap at 80%
        
        # Use average price for weighted items, base price for others
        base_price = listing.average_price if listing.average_price else listing.product.base_price
        
        # Calculate discounted price
        discounted_price = base_price * (1 - total_discount / 100)
        
        # Calculate days until expiry (best_by_date is a date, not timezone-aware, so use UTC date for consistency)
        days_until_expiry = None
        if listing.best_by_date:
            days_until_expiry = (listing.best_by_date - today_utc).days
        
        return {
            "current_discount_percent": round(total_discount, 2),
            "discounted_price": round(discounted_price, 2),
            "days_until_expiry": days_until_expiry
        }

