from sqlalchemy import Integer, String, ForeignKey, DateTime, Float, Date, Boolean, Enum as SQLEnum, JSON
from sqlalchemy.orm import Mapped, relationship, mapped_column
from sqlalchemy.sql import func
from typing import TYPE_CHECKING, Optional, List

from app.database.database import Base
from app.enums.enums import ListingTypeEnum, ListingStatusEnum, ListingInitiatorEnum, ProductStatusEnum

if TYPE_CHECKING:
    from app.models.staff.store_model import Chain, StoreProductInventory, Store
    from app.models.staff.staff_model import Staff


class ProductCategory(Base):
    __tablename__ = "product_category"

    category_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    category_name: Mapped[str] = mapped_column(String, index=True, nullable=False)
    category_image_link: Mapped[str] = mapped_column(String, nullable=True)
    created_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    products: Mapped[list["Product"]] = relationship(back_populates="category")
    taxes: Mapped[list["CategoryTax"]] = relationship(back_populates="category", cascade="all, delete-orphan")


class CategoryTax(Base):
    __tablename__ = "category_taxes"

    tax_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    category_id: Mapped[int] = mapped_column(ForeignKey("product_category.category_id", ondelete="CASCADE"), nullable=False, index=True)
    state_code: Mapped[str] = mapped_column(String(100), nullable=False, index=True)  # e.g., "SINDH", "PUNJAB", "CA", "NY"
    tax_name: Mapped[str] = mapped_column(String, nullable=False)
    tax_percent: Mapped[float] = mapped_column(Float, nullable=False)
    tax_key: Mapped[str] = mapped_column(String, nullable=False)
    created_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    category: Mapped["ProductCategory"] = relationship(back_populates="taxes")


class ProductTax(Base):
    __tablename__ = "product_taxes"

    tax_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    product_id: Mapped[int] = mapped_column(ForeignKey("products.product_id", ondelete="CASCADE"), nullable=False, index=True)
    state_code: Mapped[str] = mapped_column(String(100), nullable=False, index=True)  # e.g., "SINDH", "PUNJAB", "CA", "NY"
    tax_name: Mapped[str] = mapped_column(String, nullable=False)
    tax_percent: Mapped[float] = mapped_column(Float, nullable=False)
    tax_key: Mapped[str] = mapped_column(String, nullable=False)
    created_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )

    product: Mapped["Product"] = relationship(back_populates="taxes")


class Product(Base):
    __tablename__ = "products"

    product_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    product_name: Mapped[str] = mapped_column(String, index=True, nullable=False)
    product_description: Mapped[str] = mapped_column(String, nullable=False)
    category_id: Mapped[int] = mapped_column(ForeignKey("product_category.category_id"))
    product_barcode: Mapped[str] = mapped_column(String, unique=True, index=True, nullable=False)
    status: Mapped[ProductStatusEnum] = mapped_column(
        SQLEnum(ProductStatusEnum, name="product_status_enum"),
        nullable=False,
        default=ProductStatusEnum.PENDING,
    )
    submitted_chain_id: Mapped[Optional[int]] = mapped_column(ForeignKey("chains.chain_id"), nullable=True)
    product_image: Mapped[str] = mapped_column(String, nullable=True)
    
    # Pricing and inventory fields (moved from variants)
    base_price: Mapped[float] = mapped_column(Float, nullable=False)
    unit: Mapped[str] = mapped_column(String, nullable=False, default="unit")
    
    created_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[DateTime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    
    # Soft delete fields
    is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
    deleted_at: Mapped[Optional[DateTime]] = mapped_column(DateTime(timezone=True), nullable=True)
    
    listings: Mapped[list["ProductListing"]] = relationship(back_populates="product")
    inventories: Mapped[list["StoreProductInventory"]] = relationship(back_populates="product")

    category: Mapped["ProductCategory"] = relationship(back_populates="products")
    submitted_chain: Mapped[Optional["Chain"]] = relationship()
    chains: Mapped[List["ChainProduct"]] = relationship(
        "ChainProduct", back_populates="product", cascade="all, delete-orphan"
    )
    taxes: Mapped[list["ProductTax"]] = relationship(back_populates="product", cascade="all, delete-orphan")


class ChainProduct(Base):
    __tablename__ = "chain_products"

    chain_id: Mapped[int] = mapped_column(ForeignKey("chains.chain_id"), primary_key=True)
    product_id: Mapped[int] = mapped_column(ForeignKey("products.product_id", ondelete="CASCADE"), primary_key=True)
    created_at: Mapped[DateTime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)

    chain: Mapped["Chain"] = relationship("Chain")
    product: Mapped["Product"] = relationship("Product", back_populates="chains")




class ProductListing(Base):
    __tablename__ = "product_listings"
    
    listing_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    product_id: Mapped[int] = mapped_column(ForeignKey("products.product_id"), nullable=False)
    store_id: Mapped[int] = mapped_column(ForeignKey("stores.store_id"), nullable=False)
    employee_id: Mapped[Optional[int]] = mapped_column(ForeignKey("staff.id"), nullable=True)
    manager_id: Mapped[Optional[int]] = mapped_column(ForeignKey("staff.id"), nullable=True)
    staff_id: Mapped[Optional[int]] = mapped_column(ForeignKey("staff.id"), nullable=True)  # Who initiated the listing
    
    listing_type: Mapped[ListingTypeEnum] = mapped_column(SQLEnum(ListingTypeEnum), nullable=False)
    status: Mapped[ListingStatusEnum] = mapped_column(SQLEnum(ListingStatusEnum), nullable=False, default=ListingStatusEnum.DRAFT)
    initiator_type: Mapped[ListingInitiatorEnum] = mapped_column(SQLEnum(ListingInitiatorEnum), nullable=False)
    
    # Product listing details (moved from variants)
    quantity: Mapped[int] = mapped_column(Integer, nullable=False)
    best_by_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)  # Only for BEST_BY_PRODUCTS
    
    # Weighted items pricing array - stores individual prices for each item
    # Only used when listing_type is WEIGHTED_ITEMS
    weighted_items_prices: Mapped[Optional[List[float]]] = mapped_column(JSON, nullable=True)
    
    # Pre-calculated average price for weighted items (stored in DB for performance)
    average_price: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
    
    # Manager discount fields
    current_discount: Mapped[Optional[float]] = mapped_column(Float, nullable=True, default=0.0)
    daily_increasing_discount_percent: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
    hourly_increasing_discount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)  # For INSTANT_SALE
    weekly_schedule: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)  # Weekly calendar data
    discount_start_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)
    discount_end_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)
    
    # Go-live date set by manager
    go_live_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)
    
    # Manager options
    save_discount_for_future: Mapped[bool] = mapped_column(Boolean, default=False)
    save_duration_for_listing: Mapped[bool] = mapped_column(Boolean, default=False)
    auto_apply_for_next_batch: Mapped[bool] = mapped_column(Boolean, default=False)
    dont_resume_automatically: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
    resume_automatically: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
    
    created_at: Mapped[DateTime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[DateTime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    # Relationships
    product: Mapped["Product"] = relationship(back_populates="listings")
    employee: Mapped["Staff"] = relationship("Staff", foreign_keys=[employee_id])
    manager: Mapped[Optional["Staff"]] = relationship("Staff", foreign_keys=[manager_id])
    staff: Mapped[Optional["Staff"]] = relationship("Staff", foreign_keys=[staff_id])  # Who initiated the listing
    store: Mapped["Store"] = relationship("Store")
    discounts: Mapped[list["ManagerDiscount"]] = relationship(back_populates="listing")




class ManagerDiscount(Base):
    __tablename__ = "manager_discounts"
    
    discount_id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    listing_id: Mapped[Optional[int]] = mapped_column(ForeignKey("product_listings.listing_id"), nullable=True)
    product_id: Mapped[int] = mapped_column(ForeignKey("products.product_id"), nullable=False)
    store_id: Mapped[int] = mapped_column(ForeignKey("stores.store_id"), nullable=False)
    manager_id: Mapped[int] = mapped_column(ForeignKey("staff.id"), nullable=False)
    listing_type: Mapped[str] = mapped_column(String(50), nullable=False)  # Save listing type as string
    
    daily_increasing_discount_percent: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
    hourly_increasing_discount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)  # For INSTANT_SALE
    weekly_schedule: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)  # Weekly calendar for INSTANT_SALE
    discount_start_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)
    discount_end_date: Mapped[Optional[Date]] = mapped_column(Date, nullable=True)
    days_before_best_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)  # Offset days for go_live_date
    
    # Options
    save_for_future_listings: Mapped[bool] = mapped_column(Boolean, default=False)
    save_duration_for_listing: Mapped[bool] = mapped_column(Boolean, default=False)
    auto_apply_for_next_batch: Mapped[bool] = mapped_column(Boolean, default=False)
    
    created_at: Mapped[DateTime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[DateTime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    # Relationships
    listing: Mapped[Optional["ProductListing"]] = relationship(back_populates="discounts")
    product: Mapped["Product"] = relationship()
    store: Mapped["Store"] = relationship()
    manager: Mapped["Staff"] = relationship()
