from datetime import datetime, date, time
from typing import List, Optional, Dict
from pydantic import BaseModel, Field, field_validator, ConfigDict, model_validator
from app.enums.enums import ListingTypeEnum, ListingStatusEnum, ListingInitiatorEnum, ProductStatusEnum
from app.schemas.staff.store_schemas import StoreSchema


class ListingStatusUpdate(BaseModel):
    """Update listing status (for approving, pausing, resuming, cancelling listings)"""
    status: ListingStatusEnum = Field(..., description="New status for the listing")
    
    @field_validator('status')
    @classmethod
    def validate_status_transition(cls, v):
        # Only allow certain status changes via PATCH
        allowed_statuses = [
            ListingStatusEnum.APPROVED,
            ListingStatusEnum.PAUSED,
            ListingStatusEnum.ACTIVE,
            ListingStatusEnum.CANCELLED
        ]
        if v not in allowed_statuses:
            raise ValueError(f'Can only update to APPROVED, PAUSED, ACTIVE, or CANCELLED status. Got: {v}')
        return v


# Weekly Schedule Schema for INSTANT_SALE listings
class TimeRange(BaseModel):
    start_time: time = Field(..., description="Start time (e.g., 09:00)")
    end_time: time = Field(..., description="End time (e.g., 14:00)")
    
    @field_validator('start_time', 'end_time', mode='before')
    @classmethod
    def parse_time(cls, v):
        if isinstance(v, str):
            # Handle different time formats
            if 'T' in v:  # ISO format like "07:05:19.907Z"
                # Extract just the time part
                time_part = v.split('T')[1].split('.')[0]  # Get "07:05:19"
                return time.fromisoformat(time_part)
            else:  # Simple format like "09:00"
                return time.fromisoformat(v)
        return v
    
    @field_validator('end_time')
    @classmethod
    def end_time_after_start_time(cls, v, info):
        if hasattr(info, 'data') and 'start_time' in info.data and v <= info.data['start_time']:
            raise ValueError('End time must be after start time')
        return v

class WeeklySchedule(BaseModel):
    monday: Optional[TimeRange] = None
    tuesday: Optional[TimeRange] = None
    wednesday: Optional[TimeRange] = None
    thursday: Optional[TimeRange] = None
    friday: Optional[TimeRange] = None
    saturday: Optional[TimeRange] = None
    sunday: Optional[TimeRange] = None
    
    def has_any_schedule(self) -> bool:
        """Check if any day has a schedule"""
        return any([
            self.monday, self.tuesday, self.wednesday, self.thursday,
            self.friday, self.saturday, self.sunday
        ])


class TaxSchema(BaseModel):
    """Tax object schema"""
    tax_name: str = Field(..., description="Name of the tax")
    tax_percent: float = Field(..., ge=0, le=100, description="Tax percentage (0-100)")
    tax_key: str = Field(..., description="Unique key identifier for the tax")


class ProductCategoryBase(BaseModel):
    category_name: str = Field(..., min_length=1, max_length=100)
    category_image_link: Optional[str] = None
    taxes: Optional[Dict[str, List[TaxSchema]]] = Field(
        None, 
        description="State-based taxes dictionary. Keys are US state codes (e.g., 'CA', 'NY', 'TX'). Values are arrays of tax objects for that state.",
        examples=[{
            "CA": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "NY": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ]
        }]
    )


class ProductCategoryCreate(ProductCategoryBase):
    pass


class ProductCategoryUpdate(BaseModel):
    category_name: Optional[str] = Field(None, min_length=1, max_length=100)
    category_image_link: Optional[str] = None
    taxes: Optional[Dict[str, List[TaxSchema]]] = Field(
        None, 
        description="State-based taxes dictionary. Keys are US state codes (e.g., 'CA', 'NY', 'TX'). Values are arrays of tax objects for that state.",
        examples=[{
            "CA": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "NY": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ]
        }]
    )




class ProductCategory(ProductCategoryBase):
    model_config = ConfigDict(
        from_attributes=True,
        extra="ignore"  # Ignore extra attributes like 'products' relationship to prevent additionalProp1 errors
    )
    
    category_id: int
    created_at: datetime
    updated_at: datetime
    taxes: Optional[Dict[str, List[TaxSchema]]] = None  # Excluded by default, only loaded when needed
    
    @field_validator('taxes', mode='before')
    @classmethod
    def convert_taxes_to_dict(cls, v):
        """Convert SQLAlchemy relationship list to dict format for taxes field"""
        # If it's already a dict or None, return as is
        if v is None or isinstance(v, dict):
            return v
        
        # If it's a list (from SQLAlchemy relationship), convert to dict
        if isinstance(v, list):
            if len(v) == 0:
                return None
            
            # Convert list of CategoryTax objects to dict
            from app.models.listing.products import CategoryTax
            taxes_dict = {}
            for tax in v:
                if isinstance(tax, CategoryTax):
                    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 if taxes_dict else None
        
        # For any other type, return None
        return None




class ProductBase(BaseModel):
    product_name: str = Field(..., min_length=1, max_length=200)
    product_description: str = Field(..., min_length=1, max_length=1000)
    product_barcode: str = Field(..., min_length=1, max_length=50)
    product_image: str = Field(None, max_length=500, description="URL or path to product image")
    category_id: int = Field(..., gt=0, description="Valid category ID must be greater than 0")
    base_price: float = Field(..., gt=0)
    taxes: Optional[Dict[str, List[TaxSchema]]] = Field(
        None, 
        description="State-based taxes dictionary. Keys are state codes (e.g., 'SINDH', 'PUNJAB', 'CA', 'NY', 'TX', 'FL', 'IL', 'PA'). Values are arrays of tax objects for that state.",
        examples=[{
            "CA": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "NY": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ],
            "TX": [
                {"tax_name": "Sales Tax", "tax_percent": 6.25, "tax_key": "sales_tax"}
            ],
            "FL": [
                {"tax_name": "Sales Tax", "tax_percent": 6.0, "tax_key": "sales_tax"}
            ],
            "IL": [
                {"tax_name": "Sales Tax", "tax_percent": 6.25, "tax_key": "sales_tax"}
            ],
            "PA": [
                {"tax_name": "Sales Tax", "tax_percent": 6.0, "tax_key": "sales_tax"}
            ],
            "SINDH": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "PUNJAB": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ]
        }]
    )


class ProductCreate(ProductBase):
    pass


class ProductUpdate(BaseModel):
    product_name: Optional[str] = Field(None, min_length=1, max_length=200)
    product_description: Optional[str] = Field(None, min_length=1, max_length=1000)
    product_barcode: Optional[str] = Field(None, min_length=1, max_length=50)
    product_image: Optional[str] = Field(None, max_length=500, description="URL or path to product image")
    category_id: Optional[int] = None
    base_price: Optional[float] = Field(None, gt=0)
    taxes: Optional[Dict[str, List[TaxSchema]]] = Field(
        None, 
        description="State-based taxes dictionary. Keys are state codes (e.g., 'SINDH', 'PUNJAB', 'CA', 'NY', 'TX', 'FL', 'IL', 'PA'). Values are arrays of tax objects for that state.",
        examples=[{
            "CA": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "NY": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ],
            "TX": [
                {"tax_name": "Sales Tax", "tax_percent": 6.25, "tax_key": "sales_tax"}
            ],
            "FL": [
                {"tax_name": "Sales Tax", "tax_percent": 6.0, "tax_key": "sales_tax"}
            ],
            "IL": [
                {"tax_name": "Sales Tax", "tax_percent": 6.25, "tax_key": "sales_tax"}
            ],
            "PA": [
                {"tax_name": "Sales Tax", "tax_percent": 6.0, "tax_key": "sales_tax"}
            ],
            "SINDH": [
                {"tax_name": "Sales Tax", "tax_percent": 7.25, "tax_key": "sales_tax"},
                {"tax_name": "Local Tax", "tax_percent": 1.0, "tax_key": "local_tax"}
            ],
            "PUNJAB": [
                {"tax_name": "Sales Tax", "tax_percent": 8.0, "tax_key": "sales_tax"}
            ]
        }]
    )




class Product(ProductBase):
    product_id: int
    submitted_chain_id: Optional[int] = None
    status: ProductStatusEnum
    created_at: datetime
    updated_at: datetime
    category: Optional[ProductCategory] = None
    taxes: Optional[Dict[str, List[TaxSchema]]] = None  # Excluded by default, only loaded when needed
    
    @field_validator('taxes', mode='before')
    @classmethod
    def convert_taxes_to_dict(cls, v):
        """Convert SQLAlchemy relationship list to dict format for taxes field"""
        # If it's already a dict or None, return as is
        if v is None or isinstance(v, dict):
            return v
        
        # If it's a list (from SQLAlchemy relationship), convert to dict
        if isinstance(v, list):
            if len(v) == 0:
                return None
            
            # Convert list of ProductTax objects to dict
            from app.models.listing.products import ProductTax
            taxes_dict = {}
            for tax in v:
                if isinstance(tax, ProductTax):
                    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 if taxes_dict else None
        
        # For any other type, return None
        return None

    class Config:
        from_attributes = True


class ProductWithDiscountedPrice(Product):
    discounted_price: Optional[float] = None
    current_discount_percent: Optional[float] = None
    days_since_start: Optional[int] = None

    class Config:
        from_attributes = True


class StoreProductInventoryBase(BaseModel):
    quantity: int = Field(..., ge=0)
    store_price: float = Field(..., gt=0)


class MultiStoreInventoryCreate(BaseModel):
    product_id: int
    quantity: int = Field(..., ge=0)
    store_price: float = Field(..., gt=0)
    store_ids: List[int] = Field(..., min_items=1, description="List of store IDs to add inventory to")


class StoreProductInventory(StoreProductInventoryBase):
    inventory_id: int
    store_id: int
    product_id: int
    created_at: datetime
    updated_at: datetime
    product: Optional[Product] = None
    store: Optional[StoreSchema] = None

    class Config:
        from_attributes = True


class MultiStoreInventoryResponse(BaseModel):
    product_id: int
    quantity: int
    store_price: float
    created_inventories: List[StoreProductInventory] = []
    failed_stores: List[dict] = []
    total_stores: int
    successful_stores: int


class ProductSearchParams(BaseModel):
    search_term: Optional[str] = None
    category_id: Optional[int] = None
    status: Optional[ProductStatusEnum] = None
    min_price: Optional[float] = None
    max_price: Optional[float] = None
    limit: int = Field(20, ge=1, le=100)
    offset: int = Field(0, ge=0)


class InventoryUpdateRequest(BaseModel):
    product_id: int
    quantity: int = Field(..., ge=0)
    store_price: float = Field(..., gt=0)


# Product Listing Schemas
class ProductListingBase(BaseModel):
    product_id: int
    listing_type: ListingTypeEnum
    quantity: int = Field(..., gt=0)
    best_by_date: Optional[date] = None
    weighted_items_prices: Optional[List[float]] = None
    
    @field_validator('weighted_items_prices')
    @classmethod
    def validate_weighted_items_prices(cls, v, info):
        if hasattr(info, 'data'):
            listing_type = info.data.get('listing_type')
            quantity = info.data.get('quantity', 0)
            
            if v is not None and listing_type:
                if listing_type == ListingTypeEnum.WEIGHTED_ITEMS:
                    if v is None:
                        raise ValueError('weighted_items_prices is required for WEIGHTED_ITEMS listing type')
                    if len(v) != quantity:
                        raise ValueError('weighted_items_prices array length must match quantity')
                    if not all(price > 0 for price in v):
                        raise ValueError('All prices in weighted_items_prices must be greater than 0')
                else:
                    if v is not None:
                        raise ValueError('weighted_items_prices should only be provided for WEIGHTED_ITEMS listing type')
        return v
    
    @field_validator('quantity')
    @classmethod
    def validate_quantity_for_weighted_items(cls, v, info):
        if hasattr(info, 'data'):
            listing_type = info.data.get('listing_type')
            if listing_type == ListingTypeEnum.WEIGHTED_ITEMS:
                if v <= 0:
                    raise ValueError('Quantity must be greater than 0 for weighted items')
        return v


class EmployeeListingCreate(ProductListingBase):
    """Employee creates listing for their assigned store only"""
    pass


class ManagerListingCreate(BaseModel):
    """Manager creates listing request for multiple stores"""
    product_id: int
    listing_type: ListingTypeEnum
    store_ids: List[int] = Field(..., min_items=1, description="List of store IDs to create listings for")


class ProductListingCreate(ProductListingBase):
    pass


class EmployeeDetailsUpdate(BaseModel):
    """Employee adds quantity and dates to manager-initiated listing"""
    quantity: int = Field(..., gt=0)
    best_by_date: Optional[date] = None
    weighted_items_prices: Optional[List[float]] = None
    
    @field_validator('weighted_items_prices')
    @classmethod
    def validate_weighted_items_prices_for_update(cls, v, info):
        if hasattr(info, 'data') and v is not None:
            quantity = info.data.get('quantity')
            if quantity is None:
                raise ValueError('quantity is required when weighted_items_prices is provided')
            if len(v) != quantity:
                raise ValueError('weighted_items_prices array length must match quantity')
            if not all(price > 0 for price in v):
                raise ValueError('All prices in weighted_items_prices must be greater than 0')
        return v


class ProductListingUpdate(BaseModel):
    listing_type: Optional[ListingTypeEnum] = None
    daily_increasing_discount_percent: Optional[float] = Field(None, ge=0, le=100)
    discount_start_date: Optional[date] = None
    discount_end_date: Optional[date] = None
    go_live_date: Optional[date] = None
    save_discount_for_future: Optional[bool] = None
    auto_apply_for_next_batch: Optional[bool] = None


class EmployeeListingUpdate(BaseModel):
    """Employee updates their own listing - can change listing type and related fields"""
    listing_type: Optional[ListingTypeEnum] = None
    quantity: Optional[int] = Field(None, gt=0)
    best_by_date: Optional[date] = None
    weighted_items_prices: Optional[List[float]] = None
    
    @field_validator('weighted_items_prices')
    @classmethod
    def validate_weighted_items_prices_for_update(cls, v, info):
        if hasattr(info, 'data') and v is not None:
            quantity = info.data.get('quantity')
            listing_type = info.data.get('listing_type')
            
            if quantity is None:
                raise ValueError('quantity is required when weighted_items_prices is provided')
            if len(v) != quantity:
                raise ValueError('weighted_items_prices array length must match quantity')
            if not all(price > 0 for price in v):
                raise ValueError('All prices in weighted_items_prices must be greater than 0')
            
            # Ensure weighted_items_prices only for WEIGHTED_ITEMS type
            if listing_type and listing_type != ListingTypeEnum.WEIGHTED_ITEMS:
                raise ValueError('weighted_items_prices should only be provided for WEIGHTED_ITEMS listing type')
        return v
    
    @field_validator('best_by_date')
    @classmethod
    def validate_best_by_date(cls, v, info):
        if hasattr(info, 'data'):
            listing_type = info.data.get('listing_type')
            if listing_type == ListingTypeEnum.BEST_BY_PRODUCTS and v is None:
                raise ValueError('best_by_date is required for BEST_BY_PRODUCTS listing type')
        return v


class ManagerListingUpdate(BaseModel):
    """Manager updates a listing - can change listing type and related fields"""
    listing_type: Optional[ListingTypeEnum] = None
    quantity: Optional[int] = Field(None, gt=0)
    best_by_date: Optional[date] = None
    weighted_items_prices: Optional[List[float]] = None
    current_discount: Optional[float] = Field(None, ge=0, le=100)
    daily_increasing_discount_percent: Optional[float] = Field(None, ge=0, le=100)
    hourly_increasing_discount: Optional[float] = Field(None, ge=0, le=100)
    weekly_schedule: Optional[WeeklySchedule] = None
    go_live_date: Optional[date] = None
    save_discount_for_future: Optional[bool] = None
    save_duration_for_listing: Optional[bool] = None
    auto_apply_for_next_batch: Optional[bool] = None
    dont_resume_automatically: Optional[bool] = None
    resume_automatically: Optional[bool] = None
    
    @field_validator('weighted_items_prices')
    @classmethod
    def validate_weighted_items_prices_for_update(cls, v, info):
        if hasattr(info, 'data') and v is not None:
            quantity = info.data.get('quantity')
            listing_type = info.data.get('listing_type')
            
            if quantity is None:
                raise ValueError('quantity is required when weighted_items_prices is provided')
            if len(v) != quantity:
                raise ValueError('weighted_items_prices array length must match quantity')
            if not all(price > 0 for price in v):
                raise ValueError('All prices in weighted_items_prices must be greater than 0')
            
            # Ensure weighted_items_prices only for WEIGHTED_ITEMS type
            if listing_type and listing_type != ListingTypeEnum.WEIGHTED_ITEMS:
                raise ValueError('weighted_items_prices should only be provided for WEIGHTED_ITEMS listing type')
        return v
    
    @field_validator('best_by_date')
    @classmethod
    def validate_best_by_date(cls, v, info):
        if hasattr(info, 'data'):
            listing_type = info.data.get('listing_type')
            if listing_type == ListingTypeEnum.BEST_BY_PRODUCTS and v is None:
                raise ValueError('best_by_date is required for BEST_BY_PRODUCTS listing type')
        return v


class StaffSimple(BaseModel):
    """Simple staff schema for nested responses"""
    id: int
    username: str
    email: str
    role_type: str
    
    class Config:
        from_attributes = True


class ProductListing(ProductListingBase):
    listing_id: int
    store_id: int
    employee_id: Optional[int] = None
    manager_id: Optional[int] = None
    staff_id: Optional[int] = None  # Who initiated the listing
    status: ListingStatusEnum
    initiator_type: ListingInitiatorEnum
    current_discount: Optional[float] = None
    daily_increasing_discount_percent: Optional[float] = None
    hourly_increasing_discount: Optional[float] = None  # For INSTANT_SALE
    weekly_schedule: Optional[dict] = None  # Weekly calendar for INSTANT_SALE
    discount_start_date: Optional[date] = None
    discount_end_date: Optional[date] = None
    go_live_date: Optional[date] = None
    save_discount_for_future: bool = False
    save_duration_for_listing: bool = False
    auto_apply_for_next_batch: bool = False
    created_at: datetime
    updated_at: datetime
    product: Optional[Product] = None
    store: Optional[StoreSchema] = None
    employee: Optional[StaffSimple] = None
    manager: Optional[StaffSimple] = None
    # Average price for weighted items (calculated by service)
    average_price: Optional[float] = None

    class Config:
        from_attributes = True


class LiveProductListing(ProductListingBase):
    listing_id: int
    store_id: int
    employee_id: Optional[int] = None
    manager_id: Optional[int] = None
    staff_id: Optional[int] = None  # Who initiated the listing
    status: ListingStatusEnum
    initiator_type: ListingInitiatorEnum
    daily_increasing_discount_percent: Optional[float] = None
    discount_start_date: Optional[date] = None
    discount_end_date: Optional[date] = None
    go_live_date: Optional[date] = None
    save_discount_for_future: bool = False
    auto_apply_for_next_batch: bool = False
    created_at: datetime
    updated_at: datetime
    product: Optional[ProductWithDiscountedPrice] = None
    store: Optional[dict] = None
    employee: Optional[dict] = None
    manager: Optional[dict] = None
    discounted_price: Optional[float] = None
    current_discount_percent: Optional[float] = None
    days_since_start: Optional[int] = None
    # Average price for weighted items (calculated by service)
    average_price: Optional[float] = None

    class Config:
        from_attributes = True


# Manager Discount Schemas
class ManagerDiscountBase(BaseModel):
    product_id: int
    daily_increasing_discount_percent: float = Field(..., ge=0, le=100)
    discount_start_date: date
    discount_end_date: date
    save_for_future_listings: bool = False
    auto_apply_for_next_batch: bool = False


class ManagerDiscountCreate(ManagerDiscountBase):
    listing_id: Optional[int] = None


class ManagerDiscountUpdate(BaseModel):
    daily_increasing_discount_percent: Optional[float] = Field(None, ge=0, le=100)
    discount_start_date: Optional[date] = None
    discount_end_date: Optional[date] = None
    save_for_future_listings: Optional[bool] = None
    auto_apply_for_next_batch: Optional[bool] = None


class ManagerDiscount(ManagerDiscountBase):
    discount_id: int
    listing_id: Optional[int] = None
    store_id: int
    manager_id: int
    created_at: datetime
    updated_at: datetime
    product: Optional[Product] = None
    store: Optional[dict] = None
    manager: Optional[dict] = None

    class Config:
        from_attributes = True


# Manager Review Request Schema
class ManagerReviewRequest(BaseModel):
    listing_id: int
    current_discount: float = Field(..., ge=0, le=100, description="Starting discount percentage")
    daily_increasing_discount_percent: Optional[float] = Field(None, ge=0, le=100, description="Daily increasing discount percentage (for WEIGHTED_ITEMS, BEST_BY_PRODUCTS)")
    hourly_increasing_discount: Optional[float] = Field(None, ge=0, le=100, description="Hourly increasing discount percentage (for INSTANT_SALE)")
    weekly_schedule: Optional[WeeklySchedule] = Field(None, description="Weekly schedule for INSTANT_SALE listings")
    go_live_date: date
    save_discount_for_future: bool = False
    save_duration_for_listing: bool = False
    auto_apply_for_next_batch: bool = False
    dont_resume_automatically: Optional[bool] = None
    resume_automatically: Optional[bool] = None
    
    @field_validator('weekly_schedule')
    @classmethod
    def validate_weekly_schedule(cls, v):
        # Check if listing_type is available in context (this would need to be passed from the listing)
        # For now, just validate the schedule structure if provided
        if v and not v.has_any_schedule():
            raise ValueError('Weekly schedule must have at least one day scheduled')
        return v


# Previous Discount Suggestion Schema
class PreviousDiscountSuggestion(BaseModel):
    product_id: int
    store_id: int
    current_discount: float
    daily_increasing_discount_percent: Optional[float] = None
    hourly_increasing_discount: Optional[float] = None
    weekly_schedule: Optional[dict] = None
    go_live_date: date
    last_used_date: datetime
    save_discount_for_future: bool
    auto_apply_for_next_batch: bool
    save_duration_for_listing: bool
    dont_resume_automatically: Optional[bool] = None
    resume_automatically: Optional[bool] = None


# Employee Product with Store Information Schema
class EmployeeProductWithStore(BaseModel):
    product_id: int
    product_name: str
    product_description: str
    product_barcode: str
    product_image: Optional[str] = None
    base_price: float
    unit: str
    category_id: int
    submitted_chain_id: Optional[int] = None
    status: ProductStatusEnum
    created_at: datetime
    updated_at: datetime
    category: Optional[ProductCategory] = None
    store: Optional[dict] = None  # Single store (employee's assigned store)
    inventory_quantity: Optional[int] = None
    store_price: Optional[float] = None

    class Config:
        from_attributes = True


# Store Inventory Detail for Manager
class StoreInventoryDetail(BaseModel):
    store_id: int
    store_name: str
    store_location: str
    store_operational_hours: Optional[str] = None
    inventory_quantity: Optional[int] = None
    store_price: Optional[float] = None
    chain_id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


# Manager Product with Multiple Stores Information Schema
class ManagerProductWithStores(BaseModel):
    product_id: int
    product_name: str
    product_description: str
    product_barcode: str
    product_image: Optional[str] = None
    base_price: float
    unit: str
    category_id: int
    submitted_chain_id: Optional[int] = None
    status: ProductStatusEnum
    created_at: datetime
    updated_at: datetime
    category: Optional[ProductCategory] = None
    stores: List[StoreInventoryDetail] = []  # Multiple stores (manager's assigned stores)

    class Config:
        from_attributes = True


# Ensure forward references are resolved for Pydantic v2
Product.model_rebuild()
ProductWithDiscountedPrice.model_rebuild()
StoreProductInventory.model_rebuild()
MultiStoreInventoryResponse.model_rebuild()
EmployeeProductWithStore.model_rebuild()
ManagerProductWithStores.model_rebuild()
ProductCategory.model_rebuild()
