from sqlalchemy import Column, DateTime, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import relationship

from app.core.database import Base
from models.database.base import TimestampMixin


class MarketplaceImportJob(Base, TimestampMixin):
    __tablename__ = "marketplace_import_jobs"

    id = Column(Integer, primary_key=True, index=True)
    vendor_id = Column(Integer, ForeignKey("vendors.id"), nullable=False, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)

    # Import configuration
    marketplace = Column(String, nullable=False, index=True, default="Letzshop")
    source_url = Column(String, nullable=False)

    # Status tracking
    status = Column(
        String, nullable=False, default="pending"
    )  # pending, processing, completed, failed, completed_with_errors

    # Results
    imported_count = Column(Integer, default=0)
    updated_count = Column(Integer, default=0)
    error_count = Column(Integer, default=0)
    total_processed = Column(Integer, default=0)

    # Error handling
    error_message = Column(Text)

    # Timestamps
    started_at = Column(DateTime(timezone=True))
    completed_at = Column(DateTime(timezone=True))

    # Relationships
    vendor = relationship("Vendor", back_populates="marketplace_import_jobs")
    user = relationship("User", foreign_keys=[user_id])

    # Indexes for performance
    __table_args__ = (
        Index("idx_import_vendor_status", "vendor_id", "status"),
        Index("idx_import_vendor_created", "vendor_id", "created_at"),
        Index("idx_import_user_marketplace", "user_id", "marketplace"),
    )

    def __repr__(self):
        return (
            f"<MarketplaceImportJob(id={self.id}, vendor_id={self.vendor_id}, "
            f"marketplace='{self.marketplace}', status='{self.status}', "
            f"imported={self.imported_count})>"
        )
