from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum

from ..database import Base


class InquiryStatus:
    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    RESOLVED = "resolved"
    CLOSED = "closed"


class InquiryCategory:
    GENERAL = "general"
    VEHICLE = "vehicle"
    PAYMENT = "payment"
    SHIPPING = "shipping"
    DEALER = "dealer"
    ACCOUNT = "account"
    OTHER = "other"


class Inquiry(Base):
    """User inquiry/support ticket"""
    __tablename__ = "inquiries"

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

    # Legacy field for backward compatibility
    car_id = Column(Integer, ForeignKey("cars.id"), nullable=True)

    # Inquiry details
    category = Column(String(50), default=InquiryCategory.GENERAL)
    subject = Column(String(200), nullable=True)
    message = Column(Text, nullable=False)

    # Contact info (can be different from user's profile)
    contact_email = Column(String(255), nullable=True)
    contact_phone = Column(String(50), nullable=True)

    # Status
    status = Column(String(20), default=InquiryStatus.PENDING)

    # Admin response
    admin_response = Column(Text, nullable=True)
    responded_at = Column(DateTime(timezone=True), nullable=True)
    responded_by = Column(Integer, ForeignKey("users.id"), nullable=True)

    # Timestamps
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # Relationships
    user = relationship("User", foreign_keys=[user_id], back_populates="inquiries")
    responder = relationship("User", foreign_keys=[responded_by])
    # car relationship disabled due to schema mismatch - Car model doesn't have inquiries relationship
    # car = relationship("Car", back_populates="inquiries")


class InquiryMessage(Base):
    """Messages within an inquiry thread"""
    __tablename__ = "inquiry_messages"

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

    message = Column(Text, nullable=False)
    is_admin = Column(Boolean, default=False)

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

    # Relationships
    inquiry = relationship("Inquiry", backref="messages")
    user = relationship("User")
