import asyncio
from typing import List, Optional, Tuple

from fastapi import HTTPException, status
from sqlalchemy import and_, delete, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload, noload

from app.enums.enums import ProductStatusEnum, RoleTypeEnum
from app.models.listing.products import Product, ProductCategory, ChainProduct, CategoryTax, ProductTax
from app.models.staff.staff_model import Staff
from app.models.staff.store_model import Store, StoreProductInventory
from app.schemas.listing.product_schemas import (
    ProductCategoryCreate,
    ProductCategoryUpdate,
    ProductCreate,
    ProductSearchParams,
    ProductUpdate,
)
from app.services.activity_log_service import ActivityLogService


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

    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)
            if not chain_id:
                return
            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
            print(f"Failed to log activity: {str(e)}")

    # Product Category Methods
    @staticmethod
    def _taxes_dict_to_objects(category_id: int, taxes_dict: Optional[dict]) -> List[CategoryTax]:
        """Convert taxes dictionary to CategoryTax objects"""
        if not taxes_dict:
            return []
        
        tax_objects = []
        for state_code, tax_list in taxes_dict.items():
            if not isinstance(tax_list, list):
                continue
            for tax in tax_list:
                # Handle both dict (from JSON) and Pydantic model (from parsed request)
                if isinstance(tax, dict):
                    if "tax_name" in tax and "tax_percent" in tax and "tax_key" in tax:
                        tax_objects.append(CategoryTax(
                            category_id=category_id,
                            state_code=state_code.upper().strip(),
                            tax_name=tax["tax_name"],
                            tax_percent=float(tax["tax_percent"]),
                            tax_key=tax["tax_key"]
                        ))
                else:
                    # Handle Pydantic model (TaxSchema)
                    try:
                        tax_name = getattr(tax, 'tax_name', None)
                        tax_percent = getattr(tax, 'tax_percent', None)
                        tax_key = getattr(tax, 'tax_key', None)
                        if tax_name and tax_percent is not None and tax_key:
                            tax_objects.append(CategoryTax(
                                category_id=category_id,
                                state_code=state_code.upper().strip(),
                                tax_name=tax_name,
                                tax_percent=float(tax_percent),
                                tax_key=tax_key
                            ))
                    except Exception:
                        continue
        return tax_objects
    
    @staticmethod
    def _taxes_objects_to_dict(taxes: List[CategoryTax]) -> dict:
        """Convert CategoryTax objects to dictionary format"""
        if not taxes:
            return {}
        
        taxes_dict = {}
        for tax in taxes:
            state_code = tax.state_code.upper()
            if state_code not in taxes_dict:
                taxes_dict[state_code] = []
            taxes_dict[state_code].append({
                "tax_name": tax.tax_name,
                "tax_percent": tax.tax_percent,
                "tax_key": tax.tax_key
            })
        return taxes_dict
    
    @staticmethod
    def _product_taxes_dict_to_objects(product_id: int, taxes_dict: Optional[dict]) -> List[ProductTax]:
        """Convert taxes dictionary to ProductTax objects"""
        if not taxes_dict:
            return []
        
        tax_objects = []
        for state_code, tax_list in taxes_dict.items():
            if not isinstance(tax_list, list):
                continue
            for tax in tax_list:
                # Handle both dict (from JSON) and Pydantic model (from parsed request)
                if isinstance(tax, dict):
                    if "tax_name" in tax and "tax_percent" in tax and "tax_key" in tax:
                        tax_objects.append(ProductTax(
                            product_id=product_id,
                            state_code=state_code.upper().strip(),
                            tax_name=tax["tax_name"],
                            tax_percent=float(tax["tax_percent"]),
                            tax_key=tax["tax_key"]
                        ))
                else:
                    # Handle Pydantic model (TaxSchema)
                    try:
                        tax_name = getattr(tax, 'tax_name', None)
                        tax_percent = getattr(tax, 'tax_percent', None)
                        tax_key = getattr(tax, 'tax_key', None)
                        if tax_name and tax_percent is not None and tax_key:
                            tax_objects.append(ProductTax(
                                product_id=product_id,
                                state_code=state_code.upper().strip(),
                                tax_name=tax_name,
                                tax_percent=float(tax_percent),
                                tax_key=tax_key
                            ))
                    except Exception:
                        continue
        return tax_objects

    async def create_category(self, category_data: ProductCategoryCreate, staff_id: Optional[int] = None) -> ProductCategory:
        """Create a new product category (global)"""
        # Extract taxes before creating category
        taxes_dict = category_data.taxes
        category_dict = category_data.dict(exclude={"taxes"})
        
        db_category = ProductCategory(**category_dict)
        self.db.add(db_category)
        await self.db.flush()  # Get category_id
        
        # Create tax records if provided
        if taxes_dict:
            tax_objects = self._taxes_dict_to_objects(db_category.category_id, taxes_dict)
            for tax_obj in tax_objects:
                self.db.add(tax_obj)
        
        await self.db.commit()
        # Reload category with taxes relationship to ensure everything is fresh
        stmt = select(ProductCategory).where(ProductCategory.category_id == db_category.category_id).options(selectinload(ProductCategory.taxes))
        result = await self.db.execute(stmt)
        db_category = result.scalar_one()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # The ProductCategory schema has a validator that converts the relationship list to dict
        
        # Log activity if staff_id provided
        if staff_id:
            await self._log_activity(
                staff_id=staff_id,
                action_type="CREATE_CATEGORY",
                entity_type="CATEGORY",
                description=f"Created category: {category_data.category_name}",
                entity_id=db_category.category_id,
                metadata={"category_name": category_data.category_name}
            )
        
        return db_category

    async def get_categories(self, skip: int = 0, limit: int = 100, include_taxes: bool = False) -> List[ProductCategory]:
        """Get all product categories. Optionally include taxes (for admin APIs)."""
        stmt = select(ProductCategory)
        if include_taxes:
            stmt = stmt.options(selectinload(ProductCategory.taxes))
        else:
            stmt = stmt.options(noload(ProductCategory.taxes))  # Don't load taxes for list endpoint
        
        stmt = stmt.offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        categories = result.scalars().all()
        return categories

    async def get_category_by_id(self, category_id: int, include_taxes: bool = False) -> Optional[ProductCategory]:
        """Get category by ID. Optionally include taxes (for admin APIs)."""
        stmt = select(ProductCategory).where(ProductCategory.category_id == category_id)
        if include_taxes:
            stmt = stmt.options(selectinload(ProductCategory.taxes))
        result = await self.db.execute(stmt)
        category = result.scalar_one_or_none()
        
        if not category:
            return None
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # The ProductCategory schema has a validator that converts the relationship list to dict
        
        return category

    async def update_category(
        self, category_id: int, category_data: ProductCategoryUpdate, staff_id: Optional[int] = None
    ) -> Optional[ProductCategory]:
        """Update a product category"""
        db_category = await self.get_category_by_id(category_id)
        if not db_category:
            return None

        update_data = category_data.dict(exclude_unset=True, exclude={"taxes"})
        
        # Handle taxes separately if provided
        if "taxes" in category_data.dict(exclude_unset=True):
            # Delete existing taxes
            delete_stmt = delete(CategoryTax).where(CategoryTax.category_id == category_id)
            await self.db.execute(delete_stmt)
            
            # Create new tax records
            if category_data.taxes:
                tax_objects = self._taxes_dict_to_objects(category_id, category_data.taxes)
                for tax_obj in tax_objects:
                    self.db.add(tax_obj)
        
        # Update other fields
        for field, value in update_data.items():
            setattr(db_category, field, value)

        await self.db.commit()
        # Reload category with taxes relationship to ensure everything is fresh
        stmt = select(ProductCategory).where(ProductCategory.category_id == db_category.category_id).options(selectinload(ProductCategory.taxes))
        result = await self.db.execute(stmt)
        db_category = result.scalar_one()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # The ProductCategory schema has a validator that converts the relationship list to dict
        
        # Log activity if staff_id provided
        if staff_id:
            await self._log_activity(
                staff_id=staff_id,
                action_type="UPDATE_CATEGORY",
                entity_type="CATEGORY",
                description=f"Updated category ID {category_id}",
                entity_id=category_id,
                metadata={"updated_fields": list(update_data.keys()) + (["taxes"] if "taxes" in category_data.dict(exclude_unset=True) else [])}
            )
        
        return db_category

    async def delete_category(self, category_id: int, staff_id: Optional[int] = None) -> bool:
        """Delete a product category. Cannot delete if products are assigned to it."""
        # Check if category exists
        db_category = await self.get_category_by_id(category_id)
        if not db_category:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Category not found"
            )
        
        # Check if any non-deleted products are assigned to this category
        products_stmt = select(Product).where(
            and_(
                Product.category_id == category_id,
                Product.is_deleted == False  # Only count non-deleted products
            )
        )
        products_result = await self.db.execute(products_stmt)
        products = products_result.scalars().all()
        
        if products:
            product_count = len(products)
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Cannot delete category. {product_count} product(s) are assigned to this category. Please reassign or delete products first."
            )
        
        # No products assigned, safe to delete
        # Use DELETE statement for async session
        # Log activity before deletion if staff_id provided
        if staff_id:
            await self._log_activity(
                staff_id=staff_id,
                action_type="DELETE_CATEGORY",
                entity_type="CATEGORY",
                description=f"Deleted category ID {category_id}: {db_category.category_name}",
                entity_id=category_id,
                metadata={"category_name": db_category.category_name}
            )
        
        delete_stmt = delete(ProductCategory).where(
            ProductCategory.category_id == category_id
        )
        await self.db.execute(delete_stmt)
        await self.db.commit()
        return True


    # Product Methods
    async def _ensure_chain_association(self, product: Product, chain_id: int) -> None:
        stmt = select(ChainProduct).where(
            ChainProduct.chain_id == chain_id,
            ChainProduct.product_id == product.product_id,
        )
        result = await self.db.execute(stmt)
        if result.scalar_one_or_none():
            return

        chain_product = ChainProduct(chain_id=chain_id, product_id=product.product_id)
        self.db.add(chain_product)
        await self.db.commit()

    async def create_product(self, product_data: ProductCreate, chain_id: int) -> Product:
        """Submit a product for approval (Admin/chain flow)."""
        category = await self.get_category_by_id(product_data.category_id)
        if not category:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Category with ID {product_data.category_id} not found"
            )

        existing_stmt = select(Product).where(
            and_(
                Product.product_barcode == product_data.product_barcode,
                Product.is_deleted == False  # Only check non-deleted products for uniqueness
            )
        )
        existing_result = await self.db.execute(existing_stmt)
        existing_product = existing_result.scalar_one_or_none()

        if existing_product:
            if existing_product.status != ProductStatusEnum.APPROVED:
                if existing_product.submitted_chain_id == chain_id:
                    # Return existing product with category loaded
                    stmt = select(Product).options(
                        selectinload(Product.category).noload(ProductCategory.taxes),
                        noload(Product.taxes),
                    ).where(Product.product_id == existing_product.product_id)
                    result = await self.db.execute(stmt)
                    return result.scalar_one()
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=f"Product with barcode '{product_data.product_barcode}' already exists and is awaiting approval by another chain. Please use a different barcode."
                )

            await self._ensure_chain_association(existing_product, chain_id)
            return await self.get_product_by_id(existing_product.product_id)

        # Extract taxes before creating product (EXACT same pattern as category creation)
        taxes_dict = product_data.taxes
        product_dict = product_data.dict(exclude={"taxes"})
        product_dict["submitted_chain_id"] = chain_id
        product_dict["status"] = ProductStatusEnum.PENDING

        db_product = Product(**product_dict)
        self.db.add(db_product)
        await self.db.flush()  # Get product_id
        
        # Create tax records if provided (EXACT same pattern as category creation)
        if taxes_dict:
            tax_objects = self._product_taxes_dict_to_objects(db_product.product_id, taxes_dict)
            for tax_obj in tax_objects:
                self.db.add(tax_obj)
        
        await self.db.commit()
        
        # Expire the product object to force reload from database
        await self.db.refresh(db_product)
        
        # Reload product with taxes loaded (for admin API response)
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            selectinload(Product.taxes),
        ).where(Product.product_id == db_product.product_id)
        result = await self.db.execute(stmt)
        product = result.scalar_one()
        
        # Verify taxes were loaded
        if hasattr(product, 'taxes') and product.taxes:
            # Force evaluation of the relationship
            _ = list(product.taxes)
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # Taxes will be converted to dict or None by the validator
        return product

    async def create_product_as_superadmin(self, product_data: ProductCreate) -> Product:
        """
        Create a new product directly as Superadmin.

        - Does not associate with any specific chain (submitted_chain_id = None)
        - Immediately sets status to APPROVED
        - Enforces unique barcode across all products
        """
        category = await self.get_category_by_id(product_data.category_id)
        if not category:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Category with ID {product_data.category_id} not found"
            )

        existing_stmt = select(Product).where(
            and_(
                Product.product_barcode == product_data.product_barcode,
                Product.is_deleted == False  # Only check non-deleted products for uniqueness
            )
        )
        existing_result = await self.db.execute(existing_stmt)
        existing_product = existing_result.scalar_one_or_none()

        if existing_product:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Product with barcode '{product_data.product_barcode}' already exists"
            )

        # Extract taxes before creating product
        taxes_dict = product_data.taxes
        product_dict = product_data.dict(exclude={"taxes"})
        product_dict["submitted_chain_id"] = None
        product_dict["status"] = ProductStatusEnum.APPROVED

        db_product = Product(**product_dict)
        self.db.add(db_product)
        await self.db.flush()  # Get product_id

        # Create tax records if provided
        if taxes_dict:
            tax_objects = self._product_taxes_dict_to_objects(db_product.product_id, taxes_dict)
            for tax_obj in tax_objects:
                self.db.add(tax_obj)

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

        # Reload product with taxes loaded (for admin/superadmin API response)
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            selectinload(Product.taxes),
        ).where(Product.product_id == db_product.product_id)
        result = await self.db.execute(stmt)
        product = result.scalar_one()

        # Force evaluation of taxes relationship if present
        if hasattr(product, "taxes") and product.taxes:
            _ = list(product.taxes)

        return product

    async def soft_delete_product(self, product_id: int) -> Product:
        """
        Soft delete a product (Superadmin only).
        Sets is_deleted = True and deleted_at = current timestamp.
        Product will be hidden from all queries but existing listings/orders will still work.
        """
        from datetime import datetime, timezone
        
        # Load product with relationships eagerly
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            selectinload(Product.taxes)
        ).where(
            and_(
                Product.product_id == product_id,
                Product.is_deleted == False  # Can't delete already 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=f"Product with ID {product_id} not found or already deleted"
            )
        
        # Soft delete
        product.is_deleted = True
        product.deleted_at = datetime.now(timezone.utc)
        
        await self.db.commit()
        await self.db.refresh(product)
        
        # Reload with relationships to ensure they're available for response serialization
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            selectinload(Product.taxes)
        ).where(Product.product_id == product_id)
        result = await self.db.execute(stmt)
        product = result.scalar_one()
        
        return product

    async def get_products_for_chain(
        self,
        chain_id: int,
        search_params: Optional[ProductSearchParams] = None,
    ) -> List[Product]:
        """Get products adopted by a specific chain OR submitted by the chain - shows all statuses by default"""
        # Get products that are either:
        # 1. Adopted by the chain (have ChainProduct association)
        # 2. Submitted by the chain (submitted_chain_id == chain_id, even if pending)
        stmt = (
            select(Product)
            .outerjoin(ChainProduct, ChainProduct.product_id == Product.product_id)
            .options(
                selectinload(Product.category).noload(ProductCategory.taxes),
                selectinload(Product.taxes)  # Load taxes for admin API
            )
            .where(
                and_(
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    or_(
                        ChainProduct.chain_id == chain_id,
                        Product.submitted_chain_id == chain_id
                    )
                )
            )
        )

        if search_params:
            # Apply status filter if provided, otherwise show all statuses
            if search_params.status:
                stmt = stmt.where(Product.status == search_params.status)

            if search_params.search_term:
                search_term = f"%{search_params.search_term}%"
                stmt = stmt.where(
                    or_(
                        Product.product_name.ilike(search_term),
                        Product.product_description.ilike(search_term),
                        Product.product_barcode.ilike(search_term)
                    )
                )

            if search_params.category_id:
                stmt = stmt.where(Product.category_id == search_params.category_id)

            if search_params.min_price or search_params.max_price:
                if search_params.min_price:
                    stmt = stmt.where(Product.base_price >= search_params.min_price)
                if search_params.max_price:
                    stmt = stmt.where(Product.base_price <= search_params.max_price)

            stmt = stmt.offset(search_params.offset).limit(search_params.limit)
        else:
            stmt = stmt.limit(100)

        result = await self.db.execute(stmt.order_by(Product.created_at.desc()))
        return result.scalars().all()

    async def get_products_submitted_by_chain(
        self,
        chain_id: int,
        status_filter: Optional[ProductStatusEnum] = None,
        *,
        limit: int = 100,
        offset: int = 0,
    ) -> List[Product]:
        stmt = (
            select(Product)
            .options(
                selectinload(Product.category).noload(ProductCategory.taxes),
                noload(Product.taxes)
            )
            .where(
                and_(
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    Product.submitted_chain_id == chain_id
                )
            )
            .order_by(Product.created_at.desc())
            .offset(offset)
            .limit(limit)
        )
        if status_filter:
            stmt = stmt.where(Product.status == status_filter)
        result = await self.db.execute(stmt)
        products = result.scalars().all()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # Taxes will be converted to dict or None by the validator
        
        return products

    async def get_products_global(
        self,
        search_params: Optional[ProductSearchParams] = None,
        status_filter: Optional[ProductStatusEnum] = None,
        include_taxes: bool = False,
    ) -> List[Product]:
        """Get all products (excluding soft-deleted)"""
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes)
        ).where(Product.is_deleted == False)  # Exclude soft-deleted products
        
        # Optionally include taxes (useful for superadmin viewing approved products)
        if include_taxes:
            stmt = stmt.options(selectinload(Product.taxes))
        else:
            stmt = stmt.options(noload(Product.taxes))

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

        if search_params:
            if search_params.search_term:
                search_term = f"%{search_params.search_term}%"
                stmt = stmt.where(
                    or_(
                        Product.product_name.ilike(search_term),
                        Product.product_description.ilike(search_term),
                        Product.product_barcode.ilike(search_term)
                    )
                )

            if search_params.category_id:
                stmt = stmt.where(Product.category_id == search_params.category_id)

            if search_params.min_price or search_params.max_price:
                if search_params.min_price:
                    stmt = stmt.where(Product.base_price >= search_params.min_price)
                if search_params.max_price:
                    stmt = stmt.where(Product.base_price <= search_params.max_price)

            stmt = stmt.offset(search_params.offset).limit(search_params.limit)

        result = await self.db.execute(stmt.order_by(Product.created_at.desc()))
        return result.scalars().all()

    async def get_product_by_id(self, product_id: int, include_taxes: bool = False) -> Optional[Product]:
        """Get product by ID with category. Optionally include taxes (for admin APIs)."""
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes)
        ).where(
            and_(
                Product.product_id == product_id,
                Product.is_deleted == False  # Exclude soft-deleted products
            )
        )
        if include_taxes:
            stmt = stmt.options(selectinload(Product.taxes))
        else:
            stmt = stmt.options(noload(Product.taxes))
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def get_approved_products_for_suggestions(
        self,
        search_term: Optional[str] = None,
        limit: int = 20
    ) -> List[Product]:
        """Get approved products for admin suggestions (search only)"""
        stmt = (
            select(Product)
            .options(
                selectinload(Product.category).noload(ProductCategory.taxes),
                noload(Product.taxes)
            )
            .where(
                and_(
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False  # Exclude soft-deleted products
                )
            )
        )
        
        if search_term and search_term.strip():
            search_pattern = f"%{search_term.strip().lower()}%"
            stmt = stmt.where(
                or_(
                    Product.product_name.ilike(search_pattern),
                    Product.product_description.ilike(search_pattern),
                    Product.product_barcode.ilike(search_pattern)
                )
            )
        
        stmt = stmt.order_by(Product.product_name).limit(limit)
        result = await self.db.execute(stmt)
        products = result.scalars().all()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # Taxes will be converted to dict or None by the validator
        
        return products

    async def get_product_by_barcode(self, barcode: str) -> Optional[Product]:
        """Get product by barcode"""
        stmt = select(Product).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            noload(Product.taxes)
        ).where(
            and_(
                Product.product_barcode == barcode,
                Product.is_deleted == False  # Exclude soft-deleted products
            )
        )
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()

    async def remove_product_from_chain(self, product_id: int, chain_id: int) -> dict:
        """Remove a product from a chain (Admin only)
        
        - If product is APPROVED: Only removes ChainProduct association (product remains in database for other chains)
        - If product is PENDING and submitted by this chain: Cannot remove (must wait for approval/rejection)
        - If product is REJECTED and submitted by this chain: Removes submitted_chain_id association
        - If product is PENDING/REJECTED and submitted by another chain: Removes ChainProduct association if exists
        """
        # Get the product
        product = await self.get_product_by_id(product_id)
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        
        # Check if product is PENDING and submitted by this chain
        if product.status == ProductStatusEnum.PENDING and product.submitted_chain_id == chain_id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Cannot remove a product that you submitted and is pending approval. Please wait for superadmin approval or rejection."
            )
        
        # Check if product is associated with this chain
        is_chain_product = False
        is_submitted_by_chain = product.submitted_chain_id == chain_id
        
        # Check if ChainProduct association exists
        chain_product_stmt = select(ChainProduct).where(
            ChainProduct.chain_id == chain_id,
            ChainProduct.product_id == product_id
        )
        chain_product_result = await self.db.execute(chain_product_stmt)
        chain_product = chain_product_result.scalar_one_or_none()
        
        if chain_product:
            is_chain_product = True
        
        # If not associated via ChainProduct or submitted_chain_id, raise error
        if not is_chain_product and not is_submitted_by_chain:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Product is not associated with your chain"
            )
        
        # Remove ChainProduct association if it exists
        if is_chain_product:
            delete_stmt = delete(ChainProduct).where(
                ChainProduct.chain_id == chain_id,
                ChainProduct.product_id == product_id
            )
            await self.db.execute(delete_stmt)
        
        # Remove submitted_chain_id if product was submitted by this chain
        # For APPROVED products: clear submitted_chain_id since it's now available to all chains
        # For REJECTED products: clear submitted_chain_id to remove from chain's list
        if is_submitted_by_chain and product.status in [ProductStatusEnum.APPROVED, ProductStatusEnum.REJECTED]:
            product.submitted_chain_id = None
        
        await self.db.commit()
        
        return {
            "message": "Product removed from your chain successfully",
            "product_id": product_id,
            "chain_id": chain_id,
            "product_status": product.status.value,
            "note": "Product remains in the database and can be used by other chains" if product.status == ProductStatusEnum.APPROVED else "Product association removed"
        }

    async def delete_product(self, product_id: int) -> bool:
        """Delete a product (Superadmin only)"""
        stmt = select(Product).where(Product.product_id == product_id)
        result = await self.db.execute(stmt)
        product = result.scalar_one_or_none()
        if not product:
            return False
        await self.db.delete(product)
        await self.db.commit()
        return True

    async def update_product(
        self,
        product_id: int,
        product_data: ProductUpdate
    ) -> Optional[Product]:
        """Update a product"""
        db_product = await self.get_product_by_id(product_id)
        if not db_product:
            return None

        update_data = product_data.dict(exclude_unset=True, exclude={"taxes"})

        if "product_barcode" in update_data:
            barcode = update_data["product_barcode"]
            existing_stmt = select(Product).where(
                Product.product_barcode == barcode,
                Product.product_id != product_id,
                Product.is_deleted == False,  # Only check non-deleted products for uniqueness
            )
            existing_result = await self.db.execute(existing_stmt)
            if existing_result.scalar_one_or_none():
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="A product with this barcode already exists"
                )

        # Handle taxes separately if provided
        if "taxes" in product_data.dict(exclude_unset=True):
            # Delete existing taxes
            delete_stmt = delete(ProductTax).where(ProductTax.product_id == product_id)
            await self.db.execute(delete_stmt)
            
            # Create new tax records
            if product_data.taxes:
                tax_objects = self._product_taxes_dict_to_objects(product_id, product_data.taxes)
                for tax_obj in tax_objects:
                    self.db.add(tax_obj)

        for field, value in update_data.items():
            setattr(db_product, field, value)

        await self.db.commit()
        await self.db.refresh(db_product)
        
        # Reload product with taxes relationship to ensure everything is fresh
        stmt = select(Product).where(Product.product_id == db_product.product_id).options(
            selectinload(Product.category).noload(ProductCategory.taxes),
            selectinload(Product.taxes),  # Load taxes so they can be returned in response
        )
        result = await self.db.execute(stmt)
        db_product = result.scalar_one()
        return db_product

    async def approve_product(self, product_id: int) -> Product:
        product = await self.get_product_by_id(product_id)
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        if product.status == ProductStatusEnum.APPROVED:
            return product

        product.status = ProductStatusEnum.APPROVED
        await self.db.commit()
        if product.submitted_chain_id:
            await self._ensure_chain_association(product, product.submitted_chain_id)
        await self.db.refresh(product)
        return product

    async def reject_product(self, product_id: int) -> Product:
        product = await self.get_product_by_id(product_id)
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Product not found"
            )
        product.status = ProductStatusEnum.REJECTED
        await self.db.commit()
        await self.db.refresh(product)
        return product




    # Inventory Methods

    async def get_inventory_by_store(self, store_id: int) -> List[StoreProductInventory]:
        """Get all inventory records for a store"""
        stmt = select(StoreProductInventory).options(
            selectinload(StoreProductInventory.store),
            selectinload(StoreProductInventory.product)
        ).where(StoreProductInventory.store_id == store_id)
        result = await self.db.execute(stmt)
        products = result.scalars().all()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # Taxes will be converted to dict or None by the validator
        
        return products

    async def get_inventory_by_product(self, product_id: int) -> List[StoreProductInventory]:
        """Get all inventory records for a product"""
        stmt = select(StoreProductInventory).options(
            selectinload(StoreProductInventory.store),
            selectinload(StoreProductInventory.product)
        ).where(StoreProductInventory.product_id == product_id)
        result = await self.db.execute(stmt)
        products = result.scalars().all()
        
        # Don't modify the SQLAlchemy relationship - let Pydantic validator handle conversion
        # Taxes will be converted to dict or None by the validator
        
        return products

    async def get_inventory_record(self, store_id: int, product_id: int) -> Optional[StoreProductInventory]:
        """Get inventory record for a specific product in a specific store"""
        stmt = select(StoreProductInventory).where(
            and_(
                StoreProductInventory.store_id == store_id,
                StoreProductInventory.product_id == product_id
            )
        )
        result = await self.db.execute(stmt)
        return result.scalar_one_or_none()


    async def create_multi_store_inventory(self, inventory_data) -> dict:
        """Create inventory records for a product in multiple stores"""
        from app.schemas.listing.product_schemas import MultiStoreInventoryResponse
        
        # Check if product exists
        product = await self.get_product_by_id(inventory_data.product_id)
        if not product:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Product {inventory_data.product_id} not found"
            )

        created_inventories = []
        failed_stores = []
        
        # Process each store
        for store_id in inventory_data.store_ids:
            try:
                # Check if store exists
                from app.models.staff.store_model import 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:
                    failed_stores.append({
                        "store_id": store_id,
                        "error": f"Store {store_id} not found"
                    })
                    continue
                
                # Check if inventory already exists for this product in this store
                existing_inventory = await self.get_inventory_record(store_id, inventory_data.product_id)
                if existing_inventory:
                    failed_stores.append({
                        "store_id": store_id,
                        "error": f"Inventory already exists for product {inventory_data.product_id} in store {store_id}"
                    })
                    continue
                
                # Create inventory record
                inventory_record = StoreProductInventory(
                    store_id=store_id,
                    product_id=inventory_data.product_id,
                    quantity=inventory_data.quantity,
                    store_price=inventory_data.store_price
                )
                
                self.db.add(inventory_record)
                await self.db.flush()  # Get the ID
                await self.db.refresh(inventory_record)
                
                # Load the inventory record with relationships
                inventory_stmt = select(StoreProductInventory).options(
                    selectinload(StoreProductInventory.store),
                    selectinload(StoreProductInventory.product)
                ).where(StoreProductInventory.inventory_id == inventory_record.inventory_id)
                
                inventory_result = await self.db.execute(inventory_stmt)
                inventory_with_relations = inventory_result.scalar_one_or_none()
                
                created_inventories.append(inventory_with_relations)
                
            except Exception as e:
                failed_stores.append({
                    "store_id": store_id,
                    "error": str(e)
                })
        
        # Commit all successful creations
        await self.db.commit()
        
        return {
            "product_id": inventory_data.product_id,
            "quantity": inventory_data.quantity,
            "store_price": inventory_data.store_price,
            "created_inventories": created_inventories,
            "failed_stores": failed_stores,
            "total_stores": len(inventory_data.store_ids),
            "successful_stores": len(created_inventories)
        }

    async def get_employee_products_with_store(
        self, 
        employee_store_id: int, 
        skip: int = 0, 
        limit: int = 100,
        search: Optional[str] = None,
        category_id: Optional[List[int]] = None
    ) -> List[dict]:
        """Get approved products available for the employee's store/chain only."""
        store_stmt = select(Store).where(Store.store_id == employee_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=f"Store {employee_store_id} not found"
            )

        chain_id = store.chain_id

        stmt = (
            select(Product)
            .join(ChainProduct, ChainProduct.product_id == Product.product_id)
            .options(
                selectinload(Product.category).noload(ProductCategory.taxes),
                noload(Product.taxes)
            )
            .where(
                and_(
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    ChainProduct.chain_id == chain_id,
                )
            )
        )
        
        if category_id:
            stmt = stmt.where(Product.category_id.in_(category_id))
        
        if search:
            search_term = f"%{search.lower()}%"
            stmt = stmt.where(
                or_(
                    Product.product_name.ilike(search_term),
                    Product.product_description.ilike(search_term),
                    Product.product_barcode.ilike(search_term)
                )
            )
        
        stmt = stmt.order_by(Product.created_at.desc()).offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        products = result.scalars().all()
        
        return [
            {
                "product_id": product.product_id,
                "product_name": product.product_name,
                "product_description": product.product_description,
                "product_barcode": product.product_barcode,
                "product_image": product.product_image,
                "base_price": product.base_price,
                "unit": product.unit,
                "category_id": product.category_id,
                "submitted_chain_id": product.submitted_chain_id,
                "status": product.status,
                "created_at": product.created_at,
                "updated_at": product.updated_at,
                "category": {
                    "category_id": product.category.category_id,
                    "category_name": product.category.category_name,
                    "category_image_link": product.category.category_image_link,
                    "created_at": product.category.created_at,
                    "updated_at": product.category.updated_at
                } if product.category else None,
                "store": {
                    "store_id": store.store_id,
                    "store_name": store.store_name,
                    "store_location": store.store_location,
                    "store_operational_hours": store.store_operational_hours,
                    "inventory_quantity": None,
                    "store_price": None,
                    "chain_id": store.chain_id,
                    "created_at": store.created_at,
                    "updated_at": store.updated_at
                },
            }
            for product in products
        ]

    async def get_manager_products_with_stores(
        self, 
        manager_store_ids: List[int], 
        skip: int = 0, 
        limit: int = 100,
        search: Optional[str] = None,
        category_id: Optional[List[int]] = None
    ) -> List[dict]:
        """Get approved products available for the manager's chains only."""
        if not manager_store_ids:
            return []

        stores_stmt = select(Store).where(Store.store_id.in_(manager_store_ids))
        stores_result = await self.db.execute(stores_stmt)
        stores = stores_result.scalars().all()
        if not stores:
            return []

        # Collect unique chain IDs for the manager's stores
        chain_ids = list({store.chain_id for store in stores if store.chain_id is not None})
        if not chain_ids:
            return []

        stmt = (
            select(Product)
            .join(ChainProduct, ChainProduct.product_id == Product.product_id)
            .options(
                selectinload(Product.category).noload(ProductCategory.taxes),
                noload(Product.taxes)
            )
            .where(
                and_(
                    Product.status == ProductStatusEnum.APPROVED,
                    Product.is_deleted == False,  # Exclude soft-deleted products
                    ChainProduct.chain_id.in_(chain_ids),
                )
            )
        )
        
        if category_id:
            stmt = stmt.where(Product.category_id.in_(category_id))
        
        if search:
            search_term = f"%{search.lower()}%"
            stmt = stmt.where(
                or_(
                    Product.product_name.ilike(search_term),
                    Product.product_description.ilike(search_term),
                    Product.product_barcode.ilike(search_term)
                )
            )
        
        stmt = stmt.order_by(Product.created_at.desc()).offset(skip).limit(limit)
        result = await self.db.execute(stmt)
        products = result.scalars().all()

        store_details = [
            {
                "store_id": store.store_id,
                "store_name": store.store_name,
                "store_location": store.store_location,
                "store_operational_hours": store.store_operational_hours,
                "inventory_quantity": None,
                "store_price": None,
                "chain_id": store.chain_id,
                "created_at": store.created_at,
                "updated_at": store.updated_at,
            }
            for store in stores
        ]

        return [
            {
                "product_id": product.product_id,
                "product_name": product.product_name,
                "product_description": product.product_description,
                "product_barcode": product.product_barcode,
                "product_image": product.product_image,
                "base_price": product.base_price,
                "unit": product.unit,
                "category_id": product.category_id,
                "submitted_chain_id": product.submitted_chain_id,
                "status": product.status,
                "created_at": product.created_at,
                "updated_at": product.updated_at,
                "category": {
                    "category_id": product.category.category_id,
                    "category_name": product.category.category_name,
                    "category_image_link": product.category.category_image_link,
                    "created_at": product.category.created_at,
                    "updated_at": product.category.updated_at
                } if product.category else None,
                "stores": store_details,
            }
            for product in products
        ]
