# app/models/product.py
from fastapi import UploadFile, logger
from sqlalchemy import Column, String, Integer, Text, JSON, DateTime, Index, ForeignKey
from sqlalchemy.dialects.mysql import BIGINT
from sqlalchemy.orm import relationship
from app.db.base import Base
from app.core.time import now
import os
import uuid
from io import BytesIO

class Product(Base):
    __tablename__ = "products"
    __table_args__ = (
         Index("idx_status", "status"),
         Index("idx_points", "points_required"),
         Index("idx_product_category", "category_id", "status"),
    )

    id = Column(BIGINT(unsigned=True), primary_key=True, autoincrement=True)
    name = Column(String(255), nullable=False)
    description = Column(Text, nullable=False)
    category_id = Column(Integer, ForeignKey("product_categories.id"), nullable=False)
    points_required = Column(Integer, nullable=False)
    stock = Column(Integer, nullable=False, default=0)
    specifications = Column(JSON, nullable=True)
    status = Column(Integer, nullable=False, default=1)  # 1: Active, 2: Inactive, 3: Deleted
    created_at = Column(DateTime, nullable=False, default=now)
    updated_at = Column(DateTime, nullable=False, default=now, onupdate=now)

    category = relationship(lambda: __import__("app.models.product_category", fromlist=["ProductCategory"]).ProductCategory, back_populates="products")

    images = relationship(
        "ProductImage",
        order_by="ProductImage.sort_order",
        back_populates="product",
        cascade="all, delete-orphan"
    )

    @property
    def thumbnail(self):
        """Returns the thumbnail image for the product. If there are multiple images, returns the first one; otherwise None."""
        if self.images:
            return self.images[0].image_url
        return None

    def upload_image(self, upload_file: UploadFile, folder_path: str) -> str:
        """이미지를 업로드하고 URL을 반환합니다."""
        # MediaService 인스턴스 가져오기
        media_service = __import__("app.api.deps", fromlist=["get_media_service"]).get_media_service()
        
        # 이미지 업로드 및 URL 반환
        image_url = media_service.upload_image(upload_file, folder="product")
        return image_url
