"""
CartSessionItem ORM model.

A single line item within a cart session.  unit_price is stored in integer
cents to match the CartSession convention.
"""
from __future__ import annotations

from typing import Optional, TYPE_CHECKING

from sqlalchemy import ForeignKey, Integer, JSON, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.apps.base.models.base import Base

if TYPE_CHECKING:
    from src.apps.cart_plugin.models.cart_session import CartSession


class CartSessionItem(Base):
    """A line item attached to a CartSession."""

    __tablename__ = "cart_session_items"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)

    session_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("cart_sessions.id"), nullable=False, index=True
    )

    # Merchant-supplied product identifier (SKU, product ID, etc.) — optional.
    external_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)

    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    quantity: Mapped[int] = mapped_column(Integer, nullable=False, default=1)

    # Price per unit in integer cents.
    unit_price: Mapped[int] = mapped_column(Integer, nullable=False, default=0)

    image_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
    metadata_: Mapped[Optional[dict]] = mapped_column("metadata", JSON, nullable=True)

    # ── Relationships ──────────────────────────────────────────────────────────
    session: Mapped["CartSession"] = relationship("CartSession", back_populates="items")
