"""
캐시 모델 - 카모두 검색 결과 캐싱
"""
from sqlalchemy import Column, Integer, String, DateTime, Text, Index
from sqlalchemy.sql import func
from ..database import Base


class CarCache(Base):
    """
    검색 결과 캐시 테이블 (Maker + Model 단위)
    캐시 키: maker_code_model_code (예: "2_38" = 기아_K5)
    """
    __tablename__ = "car_cache"

    id = Column(Integer, primary_key=True, index=True)
    cache_key = Column(String(50), unique=True, nullable=False, index=True)

    maker_code = Column(String(10), nullable=False)
    maker_name = Column(String(100), nullable=False)
    model_code = Column(String(10), nullable=False)
    model_name = Column(String(100), nullable=False)

    total_count = Column(Integer, nullable=False, default=0)
    cars_data = Column(Text, nullable=False)  # JSON: 전체 차량 목록

    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    expires_at = Column(DateTime(timezone=True), nullable=False)

    __table_args__ = (
        Index('idx_car_cache_expires', 'expires_at'),
        Index('idx_car_cache_maker_model', 'maker_code', 'model_code'),
    )


class CarDetailCache(Base):
    """
    개별 차량 상세 정보 캐시 테이블
    """
    __tablename__ = "car_detail_cache"

    id = Column(Integer, primary_key=True, index=True)
    car_id = Column(String(50), unique=True, nullable=False, index=True)  # 카모두 차량 ID

    detail_data = Column(Text, nullable=False)  # JSON: 상세 정보

    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    expires_at = Column(DateTime(timezone=True), nullable=False)

    __table_args__ = (
        Index('idx_car_detail_cache_expires', 'expires_at'),
    )


class CacheRequestQueue(Base):
    """
    캐시 요청 대기열 - 동일 조건 요청 병합용
    """
    __tablename__ = "cache_request_queue"

    id = Column(Integer, primary_key=True, index=True)
    cache_key = Column(String(50), nullable=False, index=True)
    status = Column(String(20), nullable=False, default='pending')  # pending, processing, completed, failed

    created_at = Column(DateTime(timezone=True), server_default=func.now())
    started_at = Column(DateTime(timezone=True))
    completed_at = Column(DateTime(timezone=True))

    error_message = Column(Text)

    __table_args__ = (
        Index('idx_cache_request_status', 'status', 'cache_key'),
    )
