from typing import List, Optional
from datetime import date, datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sqlalchemy import and_, or_, select, func
from fastapi import HTTPException, status

from app.models.listing.products import (
    ProductListing,
    ManagerDiscount,
    Product,
    ProductCategory,
)
from app.models.staff.store_model import StoreProductInventory, Store
from app.models.staff.staff_model import Staff, StaffStore
from app.enums.enums import ListingStatusEnum, ListingTypeEnum, ProductStatusEnum
from app.schemas.listing.product_schemas import (
    ProductListingCreate,
    ProductListingUpdate,
    ManagerReviewRequest,
    PreviousDiscountSuggestion,
    ManagerListingCreate,
    EmployeeDetailsUpdate,
    EmployeeListingUpdate,
    ManagerListingUpdate,
    ListingStatusUpdate
)
from app.services.activity_log_service import ActivityLogService


class ListingService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_employee_assigned_store(self, employee_id: int) -> int:
        """Get the store ID assigned to an employee"""
        # Get staff details
        staff_stmt = select(Staff).where(Staff.id == employee_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()

        if not staff:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Employee {employee_id} not found"
            )

        if staff.role_type != "EMPLOYEE":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User is not an employee"
            )

        # Get the employee's assigned store
        store_stmt = select(StaffStore).where(StaffStore.staff_id == employee_id)
        store_result = await self.db.execute(store_stmt)
        staff_store = store_result.scalar_one_or_none()

        if not staff_store:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Employee {employee_id} is not assigned to any store"
            )

        return staff_store.store_id

    async def get_manager_assigned_stores(self, manager_id: int) -> List[int]:
        """Get all store IDs assigned to a manager"""
        # Get staff details
        staff_stmt = select(Staff).where(Staff.id == manager_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()

        if not staff:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Manager {manager_id} not found"
            )

        if staff.role_type not in ["MANAGER", "ADMIN"]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="User is not a manager or admin"
            )

        # Get all stores assigned to the manager
        store_stmt = select(StaffStore).where(StaffStore.staff_id == manager_id)
        store_result = await self.db.execute(store_stmt)
        staff_stores = store_result.scalars().all()

        if not staff_stores:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Manager {manager_id} is not assigned to any stores"
            )

        return [ss.store_id for ss in staff_stores]

    async def _get_staff_chain_id(self, staff_id: int) -> int:
        """Get chain_id for a staff member"""
        staff_stmt = select(Staff).where(Staff.id == staff_id)
        staff_result = await self.db.execute(staff_stmt)
        staff = staff_result.scalar_one_or_none()
        
        if not staff:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Staff {staff_id} not found"
            )
        
        return staff.chain_id

    async def _log_activity(
        self,
        staff_id: int,
        action_type: str,
        entity_type: str,
        description: str,
        entity_id: Optional[int] = None,
        metadata: Optional[dict] = None
    ):
        """Helper method to log activities"""
        try:
            chain_id = await self._get_staff_chain_id(staff_id)
            log_service = ActivityLogService(self.db)
            await log_service.log_activity(
                chain_id=chain_id,
                staff_id=staff_id,
                action_type=action_type,
                entity_type=entity_type,
                description=description,
                entity_id=entity_id,
                metadata=metadata
            )
        except Exception as e:
            # Don't fail the main operation if logging fails
            # Just log the error (you might want to use a proper logger)
            print(f"Failed to log activity: {str(e)}")

    # Product Listing Methods
    async def create_listing(
        self, 
        listing_data: ProductListingCreate, 
        employee_id: int
    ) -> ProductListing:
        """Create a new product listing"""
        
        # Get employee's assigned store
        store_id = await self.get_employee_assigned_store(employee_id)
        
        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",
            )

        # Validate that product exists and belongs to the store's chain
        product_stmt = select(Product).where(Product.product_id == listing_data.product_id)
        product_result = await self.db.execute(product_stmt)
        product = product_result.scalar_one_or_none()
        
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        
        if product.status != ProductStatusEnum.APPROVED:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Product must be approved before creating a listing"
            )
        
        # Validate best_by_date for BEST_BY_PRODUCTS
        if listing_data.listing_type == ListingTypeEnum.BEST_BY_PRODUCTS:
            if not listing_data.best_by_date:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="best_by_date is required for BEST_BY_PRODUCTS listing type"
                )
        
        # Create the listing
        from app.enums.enums import ListingInitiatorEnum
        
        # Calculate average price for weighted items
        average_price = None
        if (listing_data.listing_type == ListingTypeEnum.WEIGHTED_ITEMS and 
            listing_data.weighted_items_prices):
            average_price = round(sum(listing_data.weighted_items_prices) / len(listing_data.weighted_items_prices), 2)
        
        db_listing = ProductListing(
            product_id=listing_data.product_id,
            store_id=store_id,
            employee_id=employee_id,
            staff_id=employee_id,  # Track who initiated the listing
            initiator_type=ListingInitiatorEnum.EMPLOYEE,
            listing_type=listing_data.listing_type,
            quantity=listing_data.quantity,
            best_by_date=listing_data.best_by_date,
            weighted_items_prices=listing_data.weighted_items_prices,
            average_price=average_price,
            status=ListingStatusEnum.PENDING_MANAGER_REVIEW,
            save_discount_for_future=False,
            auto_apply_for_next_batch=False
        )
        
        self.db.add(db_listing)
        await self.db.commit()
        await self.db.refresh(db_listing)
        
        # Check for auto-apply discount settings
        await self._apply_auto_discount_if_available(db_listing)
        
        # Log activity
        await self._log_activity(
            staff_id=employee_id,
            action_type="CREATE_LISTING",
            entity_type="LISTING",
            description=f"Employee created listing for product ID {listing_data.product_id}",
            entity_id=db_listing.listing_id,
            metadata={
                "listing_type": listing_data.listing_type.value,
                "quantity": listing_data.quantity,
                "store_id": store_id,
                "status": ListingStatusEnum.PENDING_MANAGER_REVIEW.value
            }
        )
        
        return db_listing

    async def create_manager_listing(self, listing_data: ManagerListingCreate, manager_id: int) -> List[ProductListing]:
        """Create listing requests initiated by manager"""
        from app.enums.enums import ListingInitiatorEnum
        
        # Get manager's assigned stores
        manager_stores = await self.get_manager_assigned_stores(manager_id)
        
        # Validate that all requested stores are assigned to the manager
        invalid_stores = [store_id for store_id in listing_data.store_ids if store_id not in manager_stores]
        if invalid_stores:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Manager is not assigned to stores: {invalid_stores}"
            )
        
        # Validate product exists
        product_stmt = select(Product).where(Product.product_id == listing_data.product_id)
        product_result = await self.db.execute(product_stmt)
        product = product_result.scalar_one_or_none()
        
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        
        created_listings = []
        
        # Create a listing for each store
        for store_id in listing_data.store_ids:
            listing = ProductListing(
                product_id=listing_data.product_id,
                listing_type=listing_data.listing_type,
                store_id=store_id,
                manager_id=manager_id,
                staff_id=manager_id,  # Track who initiated the listing
                initiator_type=ListingInitiatorEnum.MANAGER,
                status=ListingStatusEnum.PENDING_EMPLOYEE_DETAILS,
                quantity=0,  # Employee will set this later
                best_by_date=None,  # Employee will set this if needed
                save_discount_for_future=False,
                auto_apply_for_next_batch=False
            )
            
            self.db.add(listing)
            await self.db.flush()  # Get the ID
            await self.db.refresh(listing)
            
            created_listings.append(listing)
        
        await self.db.commit()
        
        # Load the created listings with relationships
        listing_ids = [listing.listing_id for listing in created_listings]
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id.in_(listing_ids))
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def get_pending_employee_tasks(self, employee_id: int) -> List[ProductListing]:
        """Get listings that need employee to add details"""
        from app.enums.enums import ListingInitiatorEnum
        
        # Get employee's assigned store
        store_id = await self.get_employee_assigned_store(employee_id)
        
        # Get listings pending employee details for this store
        stmt = select(ProductListing).options(
            selectinload(ProductListing.product),
            selectinload(ProductListing.manager)
        ).where(
            and_(
                ProductListing.store_id == store_id,
                ProductListing.initiator_type == ListingInitiatorEnum.MANAGER,
                ProductListing.status == ListingStatusEnum.PENDING_EMPLOYEE_DETAILS
            )
        ).order_by(ProductListing.created_at.desc())
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def update_employee_details(self, listing_id: int, details_data: EmployeeDetailsUpdate, employee_id: int) -> ProductListing:
        """Employee adds quantity and dates to manager-initiated listing"""
        from app.enums.enums import ListingInitiatorEnum
        
        # Get the listing
        stmt = select(ProductListing).where(ProductListing.listing_id == listing_id)
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found"
            )
        
        # Validate listing is in correct state
        if listing.status != ListingStatusEnum.PENDING_EMPLOYEE_DETAILS:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Listing is not in pending employee details state"
            )
        
        # Validate employee has access to this store
        employee_store_id = await self.get_employee_assigned_store(employee_id)
        if listing.store_id != employee_store_id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Employee not assigned to this store"
            )
        
        # Calculate average price for weighted items
        average_price = None
        if (listing.listing_type == ListingTypeEnum.WEIGHTED_ITEMS and 
            details_data.weighted_items_prices):
            average_price = round(sum(details_data.weighted_items_prices) / len(details_data.weighted_items_prices), 2)
        
        # Update listing with employee details
        listing.employee_id = employee_id
        listing.staff_id = employee_id  # Update staff_id to current user
        listing.quantity = details_data.quantity
        listing.best_by_date = details_data.best_by_date
        listing.weighted_items_prices = details_data.weighted_items_prices
        listing.average_price = average_price
        listing.status = ListingStatusEnum.PENDING_MANAGER_REVIEW
        
        await self.db.commit()
        await self.db.refresh(listing)
        
        # Check for auto-apply discount settings
        await self._apply_auto_discount_if_available(listing)
        
        # Log activity
        await self._log_activity(
            staff_id=employee_id,
            action_type="UPDATE_LISTING",
            entity_type="LISTING",
            description=f"Employee updated listing details for listing ID {listing_id}",
            entity_id=listing_id,
            metadata={
                "quantity": details_data.quantity,
                "status": listing.status.value
            }
        )
        
        # Load the listing with relationships
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id == listing_id)
        
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def update_employee_listing(
        self, 
        listing_id: int, 
        update_data: EmployeeListingUpdate, 
        employee_id: int
    ) -> ProductListing:
        """Employee updates their own listing - can change listing type and related fields (only for DRAFT and PENDING_MANAGER_REVIEW)"""
        # Get the listing
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == listing_id,
                ProductListing.employee_id == employee_id,
                ProductListing.status.in_([
                    ListingStatusEnum.DRAFT,
                    ListingStatusEnum.PENDING_MANAGER_REVIEW
                ])
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found, not owned by employee, or cannot be edited"
            )
        
        # Update listing type if provided
        if update_data.listing_type is not None:
            listing.listing_type = update_data.listing_type
            
            # Clear fields that don't apply to the new listing type
            if update_data.listing_type != ListingTypeEnum.WEIGHTED_ITEMS:
                listing.weighted_items_prices = None
                listing.average_price = None
            if update_data.listing_type != ListingTypeEnum.BEST_BY_PRODUCTS:
                listing.best_by_date = None
        
        # Calculate average price for weighted items if prices are being updated
        average_price = listing.average_price  # Keep existing if not updating
        new_listing_type = update_data.listing_type if update_data.listing_type else listing.listing_type
        
        if (update_data.weighted_items_prices is not None and 
            new_listing_type == ListingTypeEnum.WEIGHTED_ITEMS):
            average_price = round(sum(update_data.weighted_items_prices) / len(update_data.weighted_items_prices), 2)
        
        # Update listing fields
        if update_data.quantity is not None:
            listing.quantity = update_data.quantity
        if update_data.best_by_date is not None:
            listing.best_by_date = update_data.best_by_date
        if update_data.weighted_items_prices is not None:
            listing.weighted_items_prices = update_data.weighted_items_prices
            listing.average_price = average_price
        
        # If listing was in PENDING_MANAGER_REVIEW, reset to PENDING_MANAGER_REVIEW after update
        if listing.status == ListingStatusEnum.PENDING_MANAGER_REVIEW:
            listing.status = ListingStatusEnum.PENDING_MANAGER_REVIEW
        
        await self.db.commit()
        await self.db.refresh(listing)
        
        # Load the listing with relationships
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id == listing_id)
        
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def update_manager_listing(
        self, 
        listing_id: int, 
        update_data: ManagerListingUpdate, 
        manager_id: int
    ) -> ProductListing:
        """Manager updates a listing - can change listing type and related fields. Status remains APPROVED if already APPROVED, otherwise changes to PENDING_MANAGER_DISCOUNT. (Allows PENDING_MANAGER_REVIEW, PENDING_MANAGER_DISCOUNT, APPROVED, PAUSED, and ACTIVE statuses in their assigned stores)"""
        # Get manager's assigned stores
        manager_stores = await self.get_manager_assigned_stores(manager_id)
        
        # Get the listing
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == listing_id,
                ProductListing.store_id.in_(manager_stores),
                ProductListing.status.in_([
                    ListingStatusEnum.PENDING_MANAGER_REVIEW,
                    ListingStatusEnum.PENDING_MANAGER_DISCOUNT,
                    ListingStatusEnum.APPROVED,
                    ListingStatusEnum.PAUSED,
                    ListingStatusEnum.ACTIVE
                ])
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found, not in your assigned stores, or cannot be edited"
            )
        
        # Update listing type if provided
        if update_data.listing_type is not None:
            listing.listing_type = update_data.listing_type
            
            # Clear fields that don't apply to the new listing type
            if update_data.listing_type != ListingTypeEnum.WEIGHTED_ITEMS:
                listing.weighted_items_prices = None
                listing.average_price = None
            if update_data.listing_type != ListingTypeEnum.BEST_BY_PRODUCTS:
                listing.best_by_date = None
        
        # Calculate average price for weighted items if prices are being updated
        average_price = listing.average_price  # Keep existing if not updating
        new_listing_type = update_data.listing_type if update_data.listing_type else listing.listing_type
        
        if (update_data.weighted_items_prices is not None and 
            new_listing_type == ListingTypeEnum.WEIGHTED_ITEMS):
            average_price = round(sum(update_data.weighted_items_prices) / len(update_data.weighted_items_prices), 2)
        
        # Update listing fields
        if update_data.quantity is not None:
            listing.quantity = update_data.quantity
        if update_data.best_by_date is not None:
            listing.best_by_date = update_data.best_by_date
        if update_data.weighted_items_prices is not None:
            listing.weighted_items_prices = update_data.weighted_items_prices
            listing.average_price = average_price
        
        # Update discount and schedule fields
        if update_data.current_discount is not None:
            listing.current_discount = update_data.current_discount
        if update_data.daily_increasing_discount_percent is not None:
            listing.daily_increasing_discount_percent = update_data.daily_increasing_discount_percent
        if update_data.hourly_increasing_discount is not None:
            listing.hourly_increasing_discount = update_data.hourly_increasing_discount
        if update_data.weekly_schedule is not None:
            # Serialize weekly schedule
            weekly_schedule_dict = {}
            for day, time_range in update_data.weekly_schedule.dict().items():
                if time_range:
                    weekly_schedule_dict[day] = {
                        "start_time": time_range["start_time"].strftime("%H:%M") if hasattr(time_range["start_time"], 'strftime') else str(time_range["start_time"]),
                        "end_time": time_range["end_time"].strftime("%H:%M") if hasattr(time_range["end_time"], 'strftime') else str(time_range["end_time"])
                    }
                else:
                    weekly_schedule_dict[day] = None
            listing.weekly_schedule = weekly_schedule_dict
        if update_data.go_live_date is not None:
            # Save go_live_date exactly as the user sends it - no timezone conversion
            listing.go_live_date = update_data.go_live_date
        if update_data.save_discount_for_future is not None:
            listing.save_discount_for_future = update_data.save_discount_for_future
        if update_data.save_duration_for_listing is not None:
            listing.save_duration_for_listing = update_data.save_duration_for_listing
        if update_data.auto_apply_for_next_batch is not None:
            listing.auto_apply_for_next_batch = update_data.auto_apply_for_next_batch
        if update_data.dont_resume_automatically is not None:
            listing.dont_resume_automatically = update_data.dont_resume_automatically
        if update_data.resume_automatically is not None:
            listing.resume_automatically = update_data.resume_automatically
        
        # Keep status as APPROVED if it's already APPROVED (no status change for APPROVED listings)
        # For other statuses, change to PENDING_MANAGER_DISCOUNT
        if listing.status == ListingStatusEnum.APPROVED or listing.status == "APPROVED":
            # Keep status as APPROVED - do nothing
            pass
        else:
            # Change to PENDING_MANAGER_DISCOUNT for all other statuses
            listing.status = ListingStatusEnum.PENDING_MANAGER_DISCOUNT
        
        await self.db.commit()
        await self.db.refresh(listing)
        
        # Load the listing with relationships
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id == listing_id)
        
        result = await self.db.execute(stmt)
        updated_listing = result.scalar_one_or_none()
        
        # Log activity
        await self._log_activity(
            staff_id=manager_id,
            action_type="UPDATE_LISTING",
            entity_type="LISTING",
            description=f"Manager updated listing ID {listing_id}",
            entity_id=listing_id,
            metadata={
                "status": listing.status.value,
                "updated_fields": list(update_data.dict(exclude_unset=True).keys())
            }
        )
        
        return updated_listing

    async def get_pending_manager_discount_listings(self, manager_id: int) -> List[ProductListing]:
        """Get listings that need manager to add discount"""
        # Get manager's assigned stores
        manager_stores = await self.get_manager_assigned_stores(manager_id)
        
        # Get listings pending manager review
        stmt = select(ProductListing).options(
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.store),
        ).where(
            and_(
                ProductListing.store_id.in_(manager_stores),
                ProductListing.status == ListingStatusEnum.PENDING_MANAGER_REVIEW
            )
        ).order_by(ProductListing.created_at.desc())
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def get_listing_by_id(self, listing_id: int) -> Optional[ProductListing]:
        """Get listing by ID"""
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id == listing_id)
        
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def get_listings_by_store(
        self, 
        store_id: int, 
        status: Optional[ListingStatusEnum] = None,
        listing_type: Optional[ListingTypeEnum] = None,
        category_id: Optional[List[int]] = None,
        search: Optional[str] = None,
        skip: int = 0, 
        limit: int = 100,
        user_id: Optional[int] = None
    ) -> List[ProductListing]:
        """Get all listings for a store"""
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.product).selectinload(Product.category),
                selectinload(ProductListing.employee),
                selectinload(ProductListing.manager),
                selectinload(ProductListing.store)
            )
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    ProductListing.store_id == store_id,
                    Product.is_deleted == False  # Exclude listings for soft-deleted products
                )
            )
        )
        
        if status:
            stmt = stmt.where(ProductListing.status == status)
            
            # Special filtering for PENDING_MANAGER_REVIEW status
            # Only show listings that were initiated by the current user
            if status == ListingStatusEnum.PENDING_MANAGER_REVIEW and user_id:
                stmt = stmt.where(ProductListing.staff_id == user_id)
        
        if listing_type:
            stmt = stmt.where(ProductListing.listing_type == listing_type)
        
        # Add category filter (supports multiple category IDs)
        if category_id:
            stmt = stmt.join(Product).where(
                and_(
                    Product.category_id.in_(category_id),
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        
        # Add search functionality
        if search:
            search_filter = or_(
                Product.product_name.ilike(f"%{search}%"),
                Product.product_description.ilike(f"%{search}%"),
                ProductCategory.category_name.ilike(f"%{search}%")
            )
            if not category_id:  # Only join if not already joined
                stmt = stmt.join(Product)
            stmt = stmt.join(ProductCategory).where(
                and_(
                    search_filter,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        
        stmt = stmt.offset(skip).limit(limit).order_by(ProductListing.created_at.desc())
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def get_pending_listings_for_manager(
        self, 
        manager_id: int,
        listing_type_filter: Optional[ListingTypeEnum] = None,
        category_id: Optional[List[int]] = None,
        store_id: Optional[List[int]] = None,
        skip: int = 0, 
        limit: int = 100
    ) -> List[ProductListing]:
        """Get pending listings for manager review"""
        # Get stores managed by this manager
        from app.models.staff.staff_model import StaffStore
        store_stmt = select(StaffStore.store_id).where(StaffStore.staff_id == manager_id)
        store_result = await self.db.execute(store_stmt)
        store_ids = [row[0] for row in store_result.fetchall()]
        
        if not store_ids:
            return []
        
        conditions = [
            ProductListing.store_id.in_(store_ids),
            ProductListing.status.in_([
                ListingStatusEnum.PENDING_MANAGER_REVIEW,
                ListingStatusEnum.PENDING_MANAGER_DISCOUNT
            ])
        ]
        
        # Add store filter if provided (supports multiple store IDs)
        if store_id:
            # Verify all requested stores are in manager's assigned stores
            valid_stores = [sid for sid in store_id if sid in store_ids]
            if valid_stores:
                conditions.append(ProductListing.store_id.in_(valid_stores))
        
        # Add listing type filter if provided
        if listing_type_filter:
            conditions.append(ProductListing.listing_type == listing_type_filter)
        
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.store),
                selectinload(ProductListing.product).selectinload(Product.category),
                selectinload(ProductListing.employee),
                selectinload(ProductListing.manager),
            )
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    *conditions,
                    Product.is_deleted == False  # Exclude listings for soft-deleted products
                )
            )
        )
        
        # Add category filter if provided (supports multiple category IDs)
        if category_id:
            stmt = stmt.where(Product.category_id.in_(category_id))
        
        stmt = stmt.offset(skip).limit(limit).order_by(ProductListing.created_at.desc())
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def get_live_listings_for_manager(
        self, 
        manager_id: int,
        listing_type_filter: Optional[ListingTypeEnum] = None,
        category_id: Optional[List[int]] = None,
        store_id: Optional[List[int]] = None,
        skip: int = 0, 
        limit: int = 100
    ) -> List[dict]:
        """Get live/approved listings for manager with discounted prices"""
        # Get stores managed by this manager
        from app.models.staff.staff_model import StaffStore
        store_stmt = select(StaffStore.store_id).where(StaffStore.staff_id == manager_id)
        store_result = await self.db.execute(store_stmt)
        store_ids = [row[0] for row in store_result.fetchall()]
        
        if not store_ids:
            return []
        
        conditions = [
            ProductListing.store_id.in_(store_ids),
            ProductListing.status.in_([
                ListingStatusEnum.APPROVED,
                ListingStatusEnum.ACTIVE,
                ListingStatusEnum.PAUSED
            ])
        ]
        
        # Add store filter if provided (supports multiple store IDs)
        if store_id:
            # Verify all requested stores are in manager's assigned stores
            valid_stores = [sid for sid in store_id if sid in store_ids]
            if valid_stores:
                conditions.append(ProductListing.store_id.in_(valid_stores))
        
        # Add listing type filter if provided
        if listing_type_filter:
            conditions.append(ProductListing.listing_type == listing_type_filter)
        
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.store),
                selectinload(ProductListing.product).selectinload(Product.category),
                selectinload(ProductListing.employee),
                selectinload(ProductListing.manager),
            )
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    *conditions,
                    Product.is_deleted == False  # Exclude listings for soft-deleted products
                )
            )
        )
        
        # Add category filter if provided (supports multiple category IDs)
        if category_id:
            stmt = stmt.where(Product.category_id.in_(category_id))
        
        stmt = stmt.offset(skip).limit(limit).order_by(ProductListing.created_at.desc())
        
        result = await self.db.execute(stmt)
        listings = result.scalars().all()
        
        # Calculate discounted prices for each listing
        live_listings = []
        for listing in listings:
            # Calculate average price for weighted items
            average_price = self._calculate_average_price_for_weighted_items(listing)
            
            listing_dict = {
                "listing_id": listing.listing_id,
                "product_id": listing.product_id,
                "store_id": listing.store_id,
                "employee_id": listing.employee_id,
                "manager_id": listing.manager_id,
                "listing_type": listing.listing_type,
                "status": listing.status,
                "initiator_type": listing.initiator_type,
                "quantity": listing.quantity,
                "best_by_date": listing.best_by_date,
                "weighted_items_prices": listing.weighted_items_prices,
                "average_price": 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,
                "go_live_date": listing.go_live_date,
                "save_discount_for_future": listing.save_discount_for_future,
                "save_duration_for_listing": listing.save_duration_for_listing,
                "auto_apply_for_next_batch": listing.auto_apply_for_next_batch,
                "dont_resume_automatically": listing.dont_resume_automatically,
                "resume_automatically": listing.resume_automatically,
                "created_at": listing.created_at,
                "updated_at": listing.updated_at,
                "product": {
                    "product_id": listing.product.product_id,
                    "product_name": listing.product.product_name,
                    "product_image": listing.product.product_image,
                    "product_description": listing.product.product_description,
                    "product_barcode": listing.product.product_barcode,
                    "base_price": listing.product.base_price,
                    "unit": listing.product.unit,
                    "category_id": listing.product.category_id,
                    "created_at": listing.product.created_at,
                    "updated_at": listing.product.updated_at,
                    "category": {
                        "category_id": listing.product.category.category_id,
                        "category_name": listing.product.category.category_name,
                        "category_image_link": listing.product.category.category_image_link,
                        "created_at": listing.product.category.created_at,
                        "updated_at": listing.product.category.updated_at
                    } if listing.product.category else None
                },
                "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,
                    "created_at": listing.store.created_at,
                    "updated_at": listing.store.updated_at
                },
            }
            
            # Calculate discounted price if discount is configured
            if listing.current_discount is not None:
                # Use average price for weighted items, base price for others
                price_for_discount = average_price if average_price else listing.product.base_price
                
                # Handle different discount types based on listing type
                if listing.listing_type == ListingTypeEnum.INSTANT_SALE and listing.hourly_increasing_discount and listing.weekly_schedule:
                    # Hourly discount for INSTANT_SALE
                    discount_info = self._calculate_hourly_discounted_price(
                        base_price=price_for_discount,
                        current_discount=listing.current_discount,
                        hourly_increasing_discount=listing.hourly_increasing_discount,
                        weekly_schedule=listing.weekly_schedule
                    )
                    
                    listing_dict.update({
                        "discounted_price": discount_info["discounted_price"],
                        "current_discount_percent": discount_info["current_discount_percent"],
                        "hours_since_start": discount_info["hours_since_start"],
                        "is_scheduled": discount_info["is_scheduled"]
                    })
                    
                    # Add discounted price to product info
                    listing_dict["product"]["discounted_price"] = discount_info["discounted_price"]
                    listing_dict["product"]["current_discount_percent"] = discount_info["current_discount_percent"]
                    listing_dict["product"]["hours_since_start"] = discount_info["hours_since_start"]
                    listing_dict["product"]["is_scheduled"] = discount_info["is_scheduled"]
                    
                elif (listing.listing_type in [ListingTypeEnum.WEIGHTED_ITEMS, ListingTypeEnum.BEST_BY_PRODUCTS] 
                      and listing.daily_increasing_discount_percent and listing.go_live_date):
                    # Daily discount for WEIGHTED_ITEMS and BEST_BY_PRODUCTS
                    discount_info = self._calculate_discounted_price(
                        base_price=price_for_discount,
                        current_discount=listing.current_discount,
                        daily_discount_percent=listing.daily_increasing_discount_percent,
                        go_live_date=listing.go_live_date,
                        listing_type=listing.listing_type
                    )
                    
                    listing_dict.update({
                        "discounted_price": discount_info["discounted_price"],
                        "current_discount_percent": discount_info["current_discount_percent"],
                        "days_since_start": discount_info["days_since_start"]
                    })
                    
                    # Add discounted price to product info
                    listing_dict["product"]["discounted_price"] = discount_info["discounted_price"]
                    listing_dict["product"]["current_discount_percent"] = discount_info["current_discount_percent"]
                    listing_dict["product"]["days_since_start"] = discount_info["days_since_start"]
            else:
                # No discount configured - use average price for weighted items, base price for others
                price_for_display = average_price if average_price else listing.product.base_price
                listing_dict.update({
                    "discounted_price": price_for_display,
                    "current_discount_percent": 0.0,
                    "days_since_start": 0
                })
                listing_dict["product"]["discounted_price"] = price_for_display
                listing_dict["product"]["current_discount_percent"] = 0.0
                listing_dict["product"]["days_since_start"] = 0
            
            live_listings.append(listing_dict)
        
        return live_listings

    async def get_all_listings_for_manager(
        self, 
        manager_id: int, 
        status_filter: Optional[ListingStatusEnum] = None,
        listing_type_filter: Optional[ListingTypeEnum] = None,
        category_id: Optional[List[int]] = None,
        search: Optional[str] = None,
        skip: int = 0, 
        limit: int = 100
    ) -> List[ProductListing]:
        """Get all listings for manager with optional status and listing type filters"""
        # Get stores managed by this manager
        from app.models.staff.staff_model import StaffStore
        store_stmt = select(StaffStore.store_id).where(StaffStore.staff_id == manager_id)
        store_result = await self.db.execute(store_stmt)
        store_ids = [row[0] for row in store_result.fetchall()]
        
        if not store_ids:
            return []
        
        conditions = [ProductListing.store_id.in_(store_ids)]
        
        if status_filter:
            conditions.append(ProductListing.status == status_filter)
        
        if listing_type_filter:
            conditions.append(ProductListing.listing_type == listing_type_filter)
        
        stmt = (
            select(ProductListing)
            .options(
                selectinload(ProductListing.store),
                selectinload(ProductListing.product).selectinload(Product.category),
                selectinload(ProductListing.employee),
                selectinload(ProductListing.manager),
            )
            .join(Product, ProductListing.product_id == Product.product_id)
            .where(
                and_(
                    *conditions,
                    Product.is_deleted == False  # Exclude listings for soft-deleted products
                )
            )
        )
        
        # Add category filter if provided (supports multiple category IDs)
        if category_id:
            stmt = stmt.where(Product.category_id.in_(category_id))
        
        # Add search functionality
        if search:
            search_filter = or_(
                Product.product_name.ilike(f"%{search}%"),
                Product.product_description.ilike(f"%{search}%"),
                ProductCategory.category_name.ilike(f"%{search}%")
            )
            stmt = stmt.join(ProductCategory).where(search_filter)
        
        stmt = stmt.offset(skip).limit(limit).order_by(ProductListing.created_at.desc())
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def submit_for_manager_review(self, listing_id: int, employee_id: int) -> ProductListing:
        """Submit listing for manager review"""
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == listing_id,
                ProductListing.employee_id == employee_id,
                ProductListing.status == ListingStatusEnum.DRAFT
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found or not in draft status"
            )
        
        listing.status = ListingStatusEnum.PENDING_MANAGER_REVIEW
        await self.db.commit()
        await self.db.refresh(listing)
        
        return await self.get_listing_by_id(listing_id)

    async def manager_review_listing(
        self, 
        review_data: ManagerReviewRequest, 
        manager_id: int
    ) -> ProductListing:
        """Manager reviews and approves/rejects listing"""
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == review_data.listing_id,
                ProductListing.status.in_([
                    ListingStatusEnum.PENDING_MANAGER_REVIEW,
                    ListingStatusEnum.PENDING_MANAGER_DISCOUNT
                ])
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found or not pending review"
            )
        
        # Validate discount percentages based on listing type
        if listing.listing_type == ListingTypeEnum.INSTANT_SALE:
            # For INSTANT_SALE, validate hourly discount and weekly schedule
            if review_data.hourly_increasing_discount is None:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="hourly_increasing_discount is required for INSTANT_SALE listings"
                )
            if review_data.hourly_increasing_discount > 100:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Hourly increasing discount cannot exceed 100%"
                )
            if not review_data.weekly_schedule or not review_data.weekly_schedule.has_any_schedule():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Weekly schedule is required for INSTANT_SALE listings"
                )
            # Clear daily discount for INSTANT_SALE
            review_data.daily_increasing_discount_percent = None
        elif listing.listing_type in [ListingTypeEnum.WEIGHTED_ITEMS, ListingTypeEnum.BEST_BY_PRODUCTS]:
            # For WEIGHTED_ITEMS and BEST_BY_PRODUCTS, validate daily discount
            if review_data.daily_increasing_discount_percent is None:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="daily_increasing_discount_percent is required for WEIGHTED_ITEMS and BEST_BY_PRODUCTS listings"
                )
            if review_data.daily_increasing_discount_percent > 100:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="Daily increasing discount cannot exceed 100%"
                )
            # Clear hourly fields for daily discount listings
            review_data.hourly_increasing_discount = None
            review_data.weekly_schedule = None
        
        # Update listing with manager's settings
        listing.manager_id = manager_id
        listing.current_discount = review_data.current_discount
        
        # Save go_live_date exactly as the user sends it - no timezone conversion
        if review_data.go_live_date:
            listing.go_live_date = review_data.go_live_date
            print(f"\n📅 Setting go_live_date for Listing {listing.listing_id}: {review_data.go_live_date}")
        else:
            # If go_live_date is not provided, set it to today's date
            from datetime import date
            listing.go_live_date = date.today()
            print(f"\n📅 No go_live_date provided for Listing {listing.listing_id}, setting to today: {listing.go_live_date}")
        listing.save_discount_for_future = review_data.save_discount_for_future
        listing.save_duration_for_listing = review_data.save_duration_for_listing
        listing.auto_apply_for_next_batch = review_data.auto_apply_for_next_batch
        listing.dont_resume_automatically = review_data.dont_resume_automatically
        listing.resume_automatically = review_data.resume_automatically
        listing.status = ListingStatusEnum.APPROVED
        
        # Set discount fields based on listing type
        if listing.listing_type == ListingTypeEnum.INSTANT_SALE:
            listing.hourly_increasing_discount = review_data.hourly_increasing_discount
            # Properly serialize weekly schedule with time objects
            if review_data.weekly_schedule:
                weekly_schedule_dict = {}
                for day, time_range in review_data.weekly_schedule.dict().items():
                    if time_range:
                        weekly_schedule_dict[day] = {
                            "start_time": time_range["start_time"].strftime("%H:%M") if hasattr(time_range["start_time"], 'strftime') else str(time_range["start_time"]),
                            "end_time": time_range["end_time"].strftime("%H:%M") if hasattr(time_range["end_time"], 'strftime') else str(time_range["end_time"])
                        }
                    else:
                        weekly_schedule_dict[day] = None
                listing.weekly_schedule = weekly_schedule_dict
            else:
                listing.weekly_schedule = None
            listing.daily_increasing_discount_percent = None  # Clear daily discount for INSTANT_SALE
        else:
            listing.daily_increasing_discount_percent = review_data.daily_increasing_discount_percent
            listing.hourly_increasing_discount = None  # Clear hourly discount for other types
            listing.weekly_schedule = None  # Clear weekly schedule for other types
        
        # Create ManagerDiscount record if saving discount or duration for future
        if review_data.save_discount_for_future or review_data.save_duration_for_listing:
            # Set discount dates based on listing type
            discount_start_date = None
            discount_end_date = None
            
            if listing.listing_type in [ListingTypeEnum.WEIGHTED_ITEMS, ListingTypeEnum.BEST_BY_PRODUCTS]:
                # For daily discount listings, use go_live_date
                discount_start_date = review_data.go_live_date
                discount_end_date = review_data.go_live_date
            # For INSTANT_SALE, leave dates as None since they use weekly schedule
            
            # Calculate offset between best_by_date and go_live_date for BEST_BY_PRODUCTS
            days_before_best_by = None
            if (listing.listing_type == ListingTypeEnum.BEST_BY_PRODUCTS and 
                listing.best_by_date and 
                review_data.go_live_date):
                # Calculate how many days before best_by_date the listing goes live
                days_before_best_by = (listing.best_by_date - review_data.go_live_date).days
            
            # Serialize weekly schedule for ManagerDiscount if needed
            manager_weekly_schedule = None
            if review_data.weekly_schedule:
                manager_weekly_schedule = {}
                for day, time_range in review_data.weekly_schedule.dict().items():
                    if time_range:
                        manager_weekly_schedule[day] = {
                            "start_time": time_range["start_time"].strftime("%H:%M") if hasattr(time_range["start_time"], 'strftime') else str(time_range["start_time"]),
                            "end_time": time_range["end_time"].strftime("%H:%M") if hasattr(time_range["end_time"], 'strftime') else str(time_range["end_time"])
                        }
                    else:
                        manager_weekly_schedule[day] = None
            
            manager_discount = ManagerDiscount(
                listing_id=listing.listing_id,
                product_id=listing.product_id,
                store_id=listing.store_id,
                manager_id=manager_id,
                listing_type=listing.listing_type.value,  # Convert enum to string
                daily_increasing_discount_percent=review_data.daily_increasing_discount_percent,
                hourly_increasing_discount=review_data.hourly_increasing_discount,
                weekly_schedule=manager_weekly_schedule,
                discount_start_date=discount_start_date,
                discount_end_date=discount_end_date,
                days_before_best_by=days_before_best_by,  # Save the offset
                save_for_future_listings=review_data.save_discount_for_future,
                save_duration_for_listing=review_data.save_duration_for_listing,
                auto_apply_for_next_batch=review_data.auto_apply_for_next_batch
            )
            self.db.add(manager_discount)
        
        await self.db.commit()
        await self.db.refresh(listing)
        
        # Log activity
        await self._log_activity(
            staff_id=manager_id,
            action_type="APPROVE_LISTING",
            entity_type="LISTING",
            description=f"Manager approved listing ID {review_data.listing_id}",
            entity_id=review_data.listing_id,
            metadata={
                "current_discount": review_data.current_discount,
                "go_live_date": str(review_data.go_live_date),
                "listing_type": listing.listing_type.value,
                "status": ListingStatusEnum.APPROVED.value
            }
        )
        
        # Check if listing is live (go_live_date is today or past) and send notifications
        # go_live_date is stored as-is (whatever date user sent), compare against today's date
        from datetime import date
        today = date.today()
        
        print(f"\n🔔 Notification Check for Listing {listing.listing_id}:")
        print(f"   go_live_date: {listing.go_live_date}")
        print(f"   Today's date: {today}")
        print(f"   condition (go_live_date <= today): {listing.go_live_date <= today if listing.go_live_date else 'N/A'}")
        if listing.go_live_date:
            if listing.go_live_date == today:
                print(f"   ✅ go_live_date matches today - listing is LIVE")
            elif listing.go_live_date < today:
                print(f"   ✅ go_live_date is in the past - listing is LIVE")
            else:
                days_until = (listing.go_live_date - today).days
                print(f"   ⏳ go_live_date is {days_until} day(s) in the future")
                print(f"   💡 Listing will go live when date reaches {listing.go_live_date}")
        
        # Compare go_live_date with today's date
        if listing.go_live_date and listing.go_live_date <= today:
            print(f"   ✅ Listing is LIVE - triggering notifications...")
            # Load store for notification
            from sqlalchemy.orm import selectinload
            stmt = select(ProductListing).options(
                selectinload(ProductListing.store),
                selectinload(ProductListing.product)
            ).where(ProductListing.listing_id == listing.listing_id)
            result = await self.db.execute(stmt)
            listing_with_store = result.scalar_one_or_none()
            
            if listing_with_store and listing_with_store.store:
                from app.services.user.notification_service import check_and_send_favorite_notifications
                # Send notifications in background (don't block the response)
                # Note: This will run after the response is sent
                try:
                    await check_and_send_favorite_notifications(
                        self.db,
                        listing_with_store,
                        listing_with_store.store
                    )
                except Exception as e:
                    # Log error but don't fail the request
                    print(f"❌ Error sending notifications: {str(e)}")
                    import traceback
                    print(f"Traceback: {traceback.format_exc()}")
            else:
                print(f"   ⚠️  Store not found or not loaded for listing {listing.listing_id}")
        else:
            if not listing.go_live_date:
                print(f"   ⚠️  SKIPPED: go_live_date is not set")
            else:
                days_until_live = (listing.go_live_date - today).days
                print(f"   ⚠️  SKIPPED: Listing goes live in {days_until_live} day(s)")
                print(f"   📊 Comparison details:")
                print(f"      - go_live_date: {listing.go_live_date}")
                print(f"      - Today: {today}")
                print(f"   💡 Notifications will be sent when date reaches {listing.go_live_date}")
                print(f"   💡 Cron job will check hourly and send notifications at 8 PM in each user's local timezone")
        
        return await self.get_listing_by_id(listing.listing_id)

    async def get_previous_discount_suggestion(
        self, 
        product_id: int, 
        store_id: int
    ) -> Optional[PreviousDiscountSuggestion]:
        """Get previous discount suggestion for a product at a store"""
        
        # First, check the most recent listing for this product/store
        # to see if save_discount_for_future or save_duration_for_listing is true
        recent_listing_stmt = select(ProductListing).where(
            and_(
                ProductListing.product_id == product_id,
                ProductListing.store_id == store_id,
                or_(
                    ProductListing.save_discount_for_future == True,
                    ProductListing.save_duration_for_listing == True
                ),
                ProductListing.status.in_([
                    ListingStatusEnum.APPROVED,
                    ListingStatusEnum.ACTIVE
                ])
            )
        ).order_by(ProductListing.created_at.desc()).limit(1)
        
        recent_result = await self.db.execute(recent_listing_stmt)
        recent_listing = recent_result.scalar_one_or_none()
        
        # If no recent listing with save_discount_for_future or save_duration_for_listing = true, return None
        if not recent_listing:
            return None
        
        # Get the corresponding ManagerDiscount record for this specific listing
        discount_stmt = select(ManagerDiscount).where(
            and_(
                ManagerDiscount.listing_id == recent_listing.listing_id,
                ManagerDiscount.product_id == product_id,
                ManagerDiscount.store_id == store_id,
                or_(
                    ManagerDiscount.save_for_future_listings == True,
                    recent_listing.save_duration_for_listing == True
                )
            )
        ).order_by(ManagerDiscount.created_at.desc()).limit(1)
        
        discount_result = await self.db.execute(discount_stmt)
        discount = discount_result.scalar_one_or_none()
        
        if not discount:
            return None
        
        # Count how many times this discount was used
        usage_count_stmt = select(func.count(ManagerDiscount.discount_id)).where(
            and_(
                ManagerDiscount.product_id == product_id,
                ManagerDiscount.store_id == store_id,
                or_(
                    ManagerDiscount.save_for_future_listings == True,
                    recent_listing.save_duration_for_listing == True
                )
            )
        )
        usage_result = await self.db.execute(usage_count_stmt)
        usage_count = usage_result.scalar()
        
        return PreviousDiscountSuggestion(
            product_id=recent_listing.product_id,
            store_id=recent_listing.store_id,
            current_discount=recent_listing.current_discount or 0.0,
            daily_increasing_discount_percent=recent_listing.daily_increasing_discount_percent,
            hourly_increasing_discount=recent_listing.hourly_increasing_discount if hasattr(recent_listing, 'hourly_increasing_discount') else None,
            weekly_schedule=recent_listing.weekly_schedule if hasattr(recent_listing, 'weekly_schedule') else None,
            go_live_date=recent_listing.go_live_date,
            last_used_date=recent_listing.created_at,
            save_discount_for_future=recent_listing.save_discount_for_future,
            auto_apply_for_next_batch=recent_listing.auto_apply_for_next_batch,
            save_duration_for_listing=recent_listing.save_duration_for_listing,
            dont_resume_automatically=recent_listing.dont_resume_automatically,
            resume_automatically=recent_listing.resume_automatically
        )

    async def delete_listing(self, listing_id: int, employee_id: int) -> bool:
        """Delete a draft or pending manager review listing"""
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == listing_id,
                ProductListing.employee_id == employee_id,
                ProductListing.status.in_([
                    ListingStatusEnum.DRAFT,
                    ListingStatusEnum.PENDING_MANAGER_REVIEW
                ])
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found or cannot be deleted"
            )
        
        
        await self.db.delete(listing)
        await self.db.commit()
        
        return True

    async def update_listing_status(
        self, 
        listing_id: int, 
        status_update: ListingStatusUpdate, 
        user_id: int,
        role_type: str
    ) -> ProductListing:
        """Update listing status (pause, resume, cancel) - available for employees and managers"""
        # Build the query based on role
        if role_type == "EMPLOYEE":
            stmt = select(ProductListing).where(
                and_(
                    ProductListing.listing_id == listing_id,
                    ProductListing.employee_id == user_id
                )
            )
        elif role_type in ["MANAGER", "ADMIN"]:
            # Get manager's assigned stores
            manager_stores = await self.get_manager_assigned_stores(user_id)
            stmt = select(ProductListing).where(
                and_(
                    ProductListing.listing_id == listing_id,
                    ProductListing.store_id.in_(manager_stores)
                )
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Unauthorized to update listing status"
            )
        
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found or you don't have permission to update it"
            )
        
        # Validate status transition
        current_status = listing.status
        new_status = status_update.status
        
        # Define valid transitions
        valid_transitions = {
            ListingStatusEnum.PENDING_MANAGER_REVIEW: [ListingStatusEnum.APPROVED, ListingStatusEnum.CANCELLED],
            ListingStatusEnum.PENDING_MANAGER_DISCOUNT: [ListingStatusEnum.APPROVED, ListingStatusEnum.CANCELLED],
            ListingStatusEnum.APPROVED: [ListingStatusEnum.PAUSED, ListingStatusEnum.CANCELLED],
            ListingStatusEnum.ACTIVE: [ListingStatusEnum.PAUSED, ListingStatusEnum.CANCELLED],
            ListingStatusEnum.PAUSED: [ListingStatusEnum.ACTIVE, ListingStatusEnum.APPROVED, ListingStatusEnum.CANCELLED],
        }
        
        if current_status not in valid_transitions:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot change status from {current_status}. Only PENDING_MANAGER_REVIEW, PENDING_MANAGER_DISCOUNT, APPROVED, ACTIVE, or PAUSED listings can be updated."
            )
        
        if new_status not in valid_transitions[current_status]:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot transition from {current_status} to {new_status}. Allowed transitions: {', '.join([s.value for s in valid_transitions[current_status]])}"
            )
        
        # Update the status
        listing.status = new_status
        
        # If approving a listing, ensure required fields are set
        if new_status == ListingStatusEnum.APPROVED:
            # Set default values if not already set
            if listing.current_discount is None:
                listing.current_discount = 0.0
            if listing.go_live_date is None:
                # Set go_live_date to today's date (no timezone conversion)
                from datetime import date
                listing.go_live_date = date.today()
        
        await self.db.commit()
        await self.db.refresh(listing)
        
        # Load the listing with relationships including taxes
        stmt = select(ProductListing).options(
            selectinload(ProductListing.store),
            selectinload(ProductListing.product).selectinload(Product.category).selectinload(ProductCategory.taxes),
            selectinload(ProductListing.product).selectinload(Product.taxes),
            selectinload(ProductListing.employee),
            selectinload(ProductListing.manager)
        ).where(ProductListing.listing_id == listing_id)
        
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def delete_manager_listing(self, listing_id: int, manager_id: int) -> bool:
        """Manager deletes a listing (allows DRAFT, PENDING_MANAGER_REVIEW, PENDING_MANAGER_DISCOUNT, APPROVED, and PAUSED listings)"""
        # Get manager's assigned stores
        manager_stores = await self.get_manager_assigned_stores(manager_id)
        
        stmt = select(ProductListing).where(
            and_(
                ProductListing.listing_id == listing_id,
                ProductListing.store_id.in_(manager_stores),
                ProductListing.status.in_([
                    ListingStatusEnum.DRAFT,
                    ListingStatusEnum.PENDING_MANAGER_REVIEW,
                    ListingStatusEnum.PENDING_MANAGER_DISCOUNT,
                    ListingStatusEnum.APPROVED,
                    ListingStatusEnum.PAUSED
                ])
            )
        )
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if not listing:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Listing not found, not in your assigned stores, or cannot be deleted"
            )
        
        # Log activity before deletion
        await self._log_activity(
            staff_id=manager_id,
            action_type="DELETE_LISTING",
            entity_type="LISTING",
            description=f"Manager deleted listing ID {listing_id}",
            entity_id=listing_id,
            metadata={
                "product_id": listing.product_id,
                "store_id": listing.store_id,
                "listing_type": listing.listing_type.value,
                "status": listing.status.value
            }
        )
        
        await self.db.delete(listing)
        await self.db.commit()
        
        return True

    async def get_active_listings_for_store(self, store_id: int) -> List[ProductListing]:
        """Get active listings for a store (for customer display)"""
        # Compare go_live_date with today's date (stored as-is, no timezone conversion)
        from datetime import date
        today = date.today()
        
        stmt = select(ProductListing).options(
            selectinload(ProductListing.product),
            selectinload(ProductListing.store)
        ).where(
            and_(
                ProductListing.store_id == store_id,
                ProductListing.status == ListingStatusEnum.ACTIVE,
                ProductListing.go_live_date <= today
            )
        ).order_by(ProductListing.go_live_date.desc())
        
        result = await self.db.execute(stmt)
        return result.scalars().all()

    async def calculate_current_discount(
        self, 
        listing_id: int, 
        current_date: Optional[date] = None
    ) -> Optional[float]:
        """Calculate current discount percentage for a listing"""
        if current_date is None:
            current_date = date.today()
        
        stmt = select(ProductListing).where(ProductListing.listing_id == listing_id)
        result = await self.db.execute(stmt)
        listing = result.scalar_one_or_none()
        
        if (not listing or 
            listing.current_discount is None or 
            not listing.daily_increasing_discount_percent or 
            not listing.go_live_date):
            return None
        
        # Only apply discount to WEIGHTED_ITEMS and BEST_BY_PRODUCTS
        if listing.listing_type not in [ListingTypeEnum.WEIGHTED_ITEMS, ListingTypeEnum.BEST_BY_PRODUCTS]:
            return 0.0
        
        # Check if current date is after go_live_date
        if current_date < listing.go_live_date:
            return 0.0
        
        # Calculate total discount: current_discount + (daily_increasing * days)
        days_passed = (current_date - listing.go_live_date).days + 1
        daily_increase = listing.daily_increasing_discount_percent * (days_passed - 1)
        total_discount = listing.current_discount + daily_increase
        
        # Cap at 100%
        return min(total_discount, 100.0)

    async def _apply_auto_discount_if_available(self, listing: ProductListing):
        """Check and apply auto-discount if available for the same product AND listing type"""
        from datetime import date
        
        # Look for previous listings of the same product AND listing type with auto_apply_for_next_batch = True
        stmt = select(ProductListing).where(
            and_(
                ProductListing.product_id == listing.product_id,
                ProductListing.store_id == listing.store_id,
                ProductListing.listing_type == listing.listing_type,  # Compare enum directly
                ProductListing.auto_apply_for_next_batch == True,
                ProductListing.status.in_([
                    ListingStatusEnum.APPROVED, 
                    ListingStatusEnum.ACTIVE
                ])
            )
        ).order_by(ProductListing.created_at.desc()).limit(1)
        
        result = await self.db.execute(stmt)
        previous_listing = result.scalar_one_or_none()
        
        if not previous_listing:
            return  # No auto-apply settings found
        
        # Apply the discount settings from the previous listing
        listing.current_discount = previous_listing.current_discount
        listing.daily_increasing_discount_percent = previous_listing.daily_increasing_discount_percent
        listing.hourly_increasing_discount = previous_listing.hourly_increasing_discount
        # weekly_schedule is already JSON serialized in the database, so we can copy it directly
        listing.weekly_schedule = previous_listing.weekly_schedule
        listing.discount_start_date = previous_listing.discount_start_date
        listing.discount_end_date = previous_listing.discount_end_date
        listing.save_discount_for_future = previous_listing.save_discount_for_future
        listing.save_duration_for_listing = previous_listing.save_duration_for_listing
        listing.auto_apply_for_next_batch = previous_listing.auto_apply_for_next_batch
        
        # Set go-live date based on saved settings
        # Get today's date for comparison
        from datetime import date, timedelta
        today = date.today()
        
        if previous_listing.save_duration_for_listing:
            # Get the ManagerDiscount record to retrieve the offset
            discount_stmt = select(ManagerDiscount).where(
                and_(
                    ManagerDiscount.product_id == listing.product_id,
                    ManagerDiscount.store_id == listing.store_id,
                    ManagerDiscount.listing_type == listing.listing_type.value,  # ManagerDiscount stores listing_type as string
                    ManagerDiscount.save_duration_for_listing == True
                )
            ).order_by(ManagerDiscount.created_at.desc()).limit(1)
            
            discount_result = await self.db.execute(discount_stmt)
            saved_discount = discount_result.scalar_one_or_none()
            
            if (saved_discount and 
                saved_discount.days_before_best_by is not None and 
                listing.listing_type == ListingTypeEnum.BEST_BY_PRODUCTS and 
                listing.best_by_date):
                # Calculate go_live_date using the offset
                calculated_go_live_date = listing.best_by_date - timedelta(days=saved_discount.days_before_best_by)
                
                # If calculated date is in the past, use today instead (listing is going live now)
                if calculated_go_live_date < today:
                    listing.go_live_date = today
                else:
                    listing.go_live_date = calculated_go_live_date
            elif previous_listing.go_live_date:
                # Fallback: use the exact date from previous listing
                # If previous listing's date is in the past, use today instead (listing is going live now)
                if previous_listing.go_live_date < today:
                    listing.go_live_date = today
                else:
                    listing.go_live_date = previous_listing.go_live_date
            else:
                # Default to today's date
                listing.go_live_date = today
        else:
            # Default to today's date
            listing.go_live_date = today
        
        # Auto-approve the listing since discount is applied
        listing.status = ListingStatusEnum.APPROVED
        
        # Set manager_id to the same manager who set the original auto-apply
        if previous_listing.manager_id:
            listing.manager_id = previous_listing.manager_id
        
        # Create ManagerDiscount record if saving for future
        if previous_listing.save_discount_for_future:
            # Calculate offset if applicable
            days_before_best_by = None
            if (listing.listing_type == ListingTypeEnum.BEST_BY_PRODUCTS and 
                listing.best_by_date and 
                listing.go_live_date):
                days_before_best_by = (listing.best_by_date - listing.go_live_date).days
            
            manager_discount = ManagerDiscount(
                listing_id=listing.listing_id,
                product_id=listing.product_id,
                store_id=listing.store_id,
                manager_id=previous_listing.manager_id,
                listing_type=listing.listing_type.value,  # Convert enum to string
                daily_increasing_discount_percent=previous_listing.daily_increasing_discount_percent,
                discount_start_date=previous_listing.discount_start_date,
                discount_end_date=previous_listing.discount_end_date,
                days_before_best_by=days_before_best_by,  # Save offset
                save_for_future_listings=previous_listing.save_discount_for_future,
                auto_apply_for_next_batch=previous_listing.auto_apply_for_next_batch
            )
            self.db.add(manager_discount)
        
        await self.db.commit()
        await self.db.refresh(listing)

    async def check_auto_apply_availability(self, product_id: int, store_id: int) -> Optional[dict]:
        """Check if auto-apply discount is available for a product at a store"""
        # Look for previous listings with auto-apply enabled
        stmt = select(ProductListing).where(
            and_(
                ProductListing.product_id == product_id,
                ProductListing.store_id == store_id,
                ProductListing.auto_apply_for_next_batch == True,
                ProductListing.status.in_([
                    ListingStatusEnum.APPROVED, 
                    ListingStatusEnum.ACTIVE
                ])
            )
        ).order_by(ProductListing.created_at.desc()).limit(1)
        
        result = await self.db.execute(stmt)
        previous_listing = result.scalar_one_or_none()
        
        if not previous_listing:
            return None
        
        return {
            "auto_apply_available": True,
            "listing_type": previous_listing.listing_type,  # Include listing type
            "discount_percent": previous_listing.daily_increasing_discount_percent,
            "discount_start_date": previous_listing.discount_start_date,
            "discount_end_date": previous_listing.discount_end_date,
            "manager_name": previous_listing.manager.username if previous_listing.manager else "Unknown",
            "last_used_date": previous_listing.created_at,
            "message": "This listing will be automatically approved with the same discount settings for matching listing type"
        }

    def _calculate_hourly_discounted_price(
        self,
        base_price: float,
        current_discount: float,
        hourly_increasing_discount: float,
        weekly_schedule: dict,
        current_datetime: datetime = None
    ) -> dict:
        """Calculate discounted price for INSTANT_SALE listings based on hourly schedule"""
        if current_datetime is None:
            current_datetime = datetime.now()
        
        # Check if current day and time is within any scheduled time range
        current_weekday = current_datetime.strftime('%A').lower()
        current_time = current_datetime.time()
        
        # Get the schedule for current day
        day_schedule = weekly_schedule.get(current_weekday)
        if not day_schedule:
            return {
                "discounted_price": base_price,
                "current_discount_percent": 0.0,
                "hours_since_start": 0,
                "is_scheduled": False
            }
        
        # Parse time range
        start_time_str = day_schedule.get('start_time')
        end_time_str = day_schedule.get('end_time')
        
        if not start_time_str or not end_time_str:
            return {
                "discounted_price": base_price,
                "current_discount_percent": 0.0,
                "hours_since_start": 0,
                "is_scheduled": False
            }
        
        # Parse times
        from datetime import datetime as dt
        start_time = dt.strptime(start_time_str, '%H:%M').time()
        end_time = dt.strptime(end_time_str, '%H:%M').time()
        
        # Check if current time is within the scheduled range
        if current_time < start_time or current_time >= end_time:
            return {
                "discounted_price": base_price,
                "current_discount_percent": 0.0,
                "hours_since_start": 0,
                "is_scheduled": False
            }
        
        # Calculate hours since start time
        current_datetime_minutes = current_time.hour * 60 + current_time.minute
        start_datetime_minutes = start_time.hour * 60 + start_time.minute
        hours_since_start = max(0, (current_datetime_minutes - start_datetime_minutes) / 60)
        
        # Calculate total discount: current_discount + (hourly_increasing * hours)
        hourly_increase = hourly_increasing_discount * hours_since_start
        total_discount_percent = min(current_discount + hourly_increase, 100.0)
        discounted_price = base_price * (1 - total_discount_percent / 100)
        
        return {
            "discounted_price": round(discounted_price, 2),
            "current_discount_percent": total_discount_percent,
            "hours_since_start": hours_since_start,
            "is_scheduled": True
        }

    def _calculate_discounted_price(
        self, 
        base_price: float, 
        current_discount: float,
        daily_discount_percent: float, 
        go_live_date: date,
        listing_type: str,
        current_date: date = None
    ) -> dict:
        """Calculate discounted price based on current discount + daily increasing discount from go_live_date"""
        if current_date is None:
            current_date = date.today()
        
        # Only apply discount to WEIGHTED_ITEMS and BEST_BY_PRODUCTS
        if listing_type not in [ListingTypeEnum.WEIGHTED_ITEMS, ListingTypeEnum.BEST_BY_PRODUCTS]:
            return {
                "discounted_price": base_price,
                "current_discount_percent": 0.0,
                "days_since_start": 0
            }
        
        # If current date is before go_live_date, return base price
        if current_date < go_live_date:
            return {
                "discounted_price": base_price,
                "current_discount_percent": 0.0,
                "days_since_start": 0
            }
        
        # Calculate total discount: current_discount + (daily_increasing * days)
        # Day 0 (go_live_date): current_discount only
        # Day 1: current_discount + (daily_discount_percent * 1)
        # Day 2: current_discount + (daily_discount_percent * 2), etc.
        # Maximum discount is capped at 80%
        days_since_start = (current_date - go_live_date).days
        daily_increase = daily_discount_percent * days_since_start
        total_discount_percent = min(current_discount + daily_increase, 80.0)  # Max 80% discount
        discounted_price = base_price * (1 - total_discount_percent / 100)
        
        return {
            "discounted_price": round(discounted_price, 2),
            "current_discount_percent": total_discount_percent,
            "days_since_start": days_since_start
        }
    
    def _calculate_average_price_for_weighted_items(self, listing: ProductListing) -> Optional[float]:
        """Calculate average price for weighted items listing"""
        if listing.listing_type != ListingTypeEnum.WEIGHTED_ITEMS or not listing.weighted_items_prices:
            return None
        
        if not listing.weighted_items_prices:
            return None
        
        return round(sum(listing.weighted_items_prices) / len(listing.weighted_items_prices), 2)
