import enum
from datetime import datetime, timezone
from decimal import Decimal

from sqlalchemy import Enum as SqlEnum

from ..extensions import db


def _utcnow():
    return datetime.now(timezone.utc)


class ItemStatus(str, enum.Enum):
    AVAILABLE = "available"
    RESERVED = "reserved"
    SOLD = "sold"
    DAMAGED = "damaged"
    RETURNED = "returned"
    IN_WARRANTY = "in_warranty"
    IN_SERVICE = "in_service"
    LOST = "lost"


# Estados en los que la unidad NO puede venderse, transferirse, declararse
# perdida, ni eliminarse. Mantener centralizado evita drift entre endpoints.
LOCKED_ITEM_STATUSES = frozenset({
    ItemStatus.SOLD,
    ItemStatus.IN_SERVICE,
    ItemStatus.IN_WARRANTY,
    ItemStatus.LOST,
})


def is_locked_for_disposition(item) -> bool:
    """¿Está la unidad bloqueada para venta/transferencia/baja?"""
    return item is not None and item.status in LOCKED_ITEM_STATUSES


class ProductKind(str, enum.Enum):
    SIMPLE = "simple"
    COMBO = "combo"


class MovementType(str, enum.Enum):
    IN = "in"
    OUT = "out"
    RESERVE = "reserve"
    RELEASE = "release"
    ADJUST_IN = "adjust_in"
    ADJUST_OUT = "adjust_out"
    DAMAGE = "damage"
    WARRANTY_OUT = "warranty_out"
    WARRANTY_IN = "warranty_in"
    SERVICE_OUT = "service_out"
    SERVICE_IN = "service_in"
    LOSS = "loss"
    RETURN_IN = "return_in"
    TRANSFER_OUT = "transfer_out"
    TRANSFER_IN = "transfer_in"
    INTERNAL_MOVE = "internal_move"


class Product(db.Model):
    __tablename__ = "products"

    id = db.Column(db.Integer, primary_key=True)
    sku = db.Column(db.String(60), unique=True, nullable=False, index=True)
    name = db.Column(db.String(190), nullable=False, index=True)
    slug = db.Column(db.String(190), unique=True, nullable=False, index=True)
    model = db.Column(db.String(120), nullable=True, index=True)
    description = db.Column(db.Text, nullable=True)
    brand_id = db.Column(db.Integer, db.ForeignKey("brands.id"), nullable=False, index=True)
    category_id = db.Column(db.Integer, db.ForeignKey("categories.id"), nullable=False, index=True)
    price = db.Column(db.Numeric(12, 2), nullable=False, default=Decimal("0.00"))
    image_url = db.Column(db.String(500), nullable=True)
    is_active = db.Column(db.Boolean, nullable=False, default=True, index=True)
    # Tipo de producto: simple (con unidades serializadas) o combo (compone otros)
    kind = db.Column(
        SqlEnum(ProductKind, native_enum=False, length=20),
        nullable=False, default=ProductKind.SIMPLE, index=True,
    )
    # Activa la seccion especial "iPhones usados": cada unidad lleva
    # color y porcentaje de bateria propios.
    is_iphone = db.Column(db.Boolean, nullable=False, default=False, index=True)
    # % de comisión que paga este producto al vendedor por cada venta POS.
    # 0 = no genera comisión. Solo aplica al canal POS (web no paga comisión).
    commission_percent = db.Column(
        db.Numeric(5, 2), nullable=False, default=Decimal("0.00"),
    )
    created_at = db.Column(db.DateTime, nullable=False, default=_utcnow)
    updated_at = db.Column(db.DateTime, nullable=False, default=_utcnow, onupdate=_utcnow)

    brand = db.relationship("Brand", backref="products")
    category = db.relationship("Category", backref="products")
    items = db.relationship("ProductItem", back_populates="product", cascade="all, delete-orphan")

    # Componentes si es combo (combo_id -> componentes)
    combo_components = db.relationship(
        "ProductComboItem",
        foreign_keys="ProductComboItem.combo_product_id",
        back_populates="combo_product",
        cascade="all, delete-orphan",
        order_by="ProductComboItem.id",
    )

    @property
    def is_combo(self) -> bool:
        return self.kind == ProductKind.COMBO

    @property
    def stock_available(self) -> int:
        if self.is_combo:
            if not self.combo_components:
                return 0
            sub = []
            for c in self.combo_components:
                if not c.component_product:
                    return 0
                comp_stock = c.component_product.stock_available
                qty = max(int(c.quantity or 1), 1)
                sub.append(comp_stock // qty)
            return min(sub) if sub else 0
        return sum(1 for it in self.items if it.status == ItemStatus.AVAILABLE)

    @property
    def components_subtotal(self) -> Decimal:
        """Suma del precio de los componentes * cantidad. Útil para mostrar ahorro vs precio del combo."""
        if not self.is_combo:
            return Decimal("0.00")
        total = Decimal("0.00")
        for c in self.combo_components:
            if c.component_product:
                total += Decimal(c.component_product.price) * c.quantity
        return total

    def __repr__(self):
        return f"<Product {self.sku} {self.name} kind={self.kind.value}>"


class ProductComboItem(db.Model):
    """Componentes de un producto-combo. Cada fila apunta a un producto simple
    con la cantidad que el combo consume al venderse."""
    __tablename__ = "product_combo_items"

    id = db.Column(db.Integer, primary_key=True)
    combo_product_id = db.Column(
        db.Integer, db.ForeignKey("products.id", ondelete="CASCADE"),
        nullable=False, index=True,
    )
    component_product_id = db.Column(
        db.Integer, db.ForeignKey("products.id"), nullable=False, index=True,
    )
    quantity = db.Column(db.Integer, nullable=False, default=1)
    created_at = db.Column(db.DateTime, nullable=False, default=_utcnow)

    __table_args__ = (
        db.UniqueConstraint("combo_product_id", "component_product_id", name="uq_combo_component"),
        db.CheckConstraint("quantity > 0", name="ck_combo_qty_positive"),
    )

    combo_product = db.relationship(
        "Product", foreign_keys=[combo_product_id], back_populates="combo_components",
    )
    component_product = db.relationship("Product", foreign_keys=[component_product_id])


class ProductItem(db.Model):
    __tablename__ = "product_items"

    id = db.Column(db.Integer, primary_key=True)
    product_id = db.Column(db.Integer, db.ForeignKey("products.id"), nullable=False, index=True)
    serial = db.Column(db.String(120), unique=True, nullable=False, index=True)
    imei = db.Column(db.String(40), unique=True, nullable=True, index=True)
    barcode = db.Column(db.String(60), unique=True, nullable=False, index=True)
    cost = db.Column(db.Numeric(12, 2), nullable=True)
    status = db.Column(
        SqlEnum(ItemStatus, native_enum=False, length=20),
        nullable=False,
        default=ItemStatus.AVAILABLE,
        index=True,
    )
    # `location` queda como texto legacy (compatibilidad). El campo documentado
    # ahora es `location_id` -> WarehouseLocation. `warehouse_id` indica el almacén.
    location = db.Column(db.String(80), nullable=True)
    notes = db.Column(db.Text, nullable=True)
    # Solo se usan en unidades de productos marcados is_iphone=True.
    color = db.Column(db.String(40), nullable=True, index=True)
    battery_pct = db.Column(db.SmallInteger, nullable=True, index=True)
    # Precio especifico de esta unidad. Si es NULL se usa product.price.
    # Util en iPhones usados donde cada equipo tiene precio distinto segun
    # estado, capacidad y bateria.
    sale_price = db.Column(db.Numeric(12, 2), nullable=True)

    @property
    def effective_price(self):
        """Precio real de venta de esta unidad."""
        if self.sale_price is not None:
            return self.sale_price
        return self.product.price if self.product else None
    store_id = db.Column(db.Integer, db.ForeignKey("stores.id"), nullable=True, index=True)
    warehouse_id = db.Column(db.Integer, db.ForeignKey("warehouses.id"), nullable=True, index=True)
    location_id = db.Column(
        db.Integer, db.ForeignKey("warehouse_locations.id"), nullable=True, index=True
    )
    created_at = db.Column(db.DateTime, nullable=False, default=_utcnow)
    updated_at = db.Column(db.DateTime, nullable=False, default=_utcnow, onupdate=_utcnow)

    product = db.relationship("Product", back_populates="items")
    store = db.relationship("Store", foreign_keys=[store_id])
    warehouse = db.relationship("Warehouse", foreign_keys=[warehouse_id])
    location_ref = db.relationship("WarehouseLocation", foreign_keys=[location_id])
    movements = db.relationship("StockMovement", back_populates="item", cascade="all, delete-orphan")

    def __repr__(self):
        return f"<ProductItem {self.serial} status={self.status.value}>"


class StockMovement(db.Model):
    __tablename__ = "stock_movements"

    id = db.Column(db.Integer, primary_key=True)
    product_item_id = db.Column(db.Integer, db.ForeignKey("product_items.id"), nullable=False, index=True)
    type = db.Column(SqlEnum(MovementType, native_enum=False, length=20), nullable=False, index=True)
    reference_type = db.Column(db.String(40), nullable=True, index=True)
    reference_id = db.Column(db.Integer, nullable=True, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True, index=True)
    notes = db.Column(db.Text, nullable=True)
    created_at = db.Column(db.DateTime, nullable=False, default=_utcnow, index=True)

    item = db.relationship("ProductItem", back_populates="movements")
    user = db.relationship("User")

    def __repr__(self):
        return f"<StockMovement #{self.id} {self.type.value} item={self.product_item_id}>"
