from pydantic import BaseModel
from typing import Optional, List
from datetime import date, datetime

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

from db.db_connection import Base

# ===============================
# SQLAlchemy ORM Model
# ===============================
class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    booking_id = Column(String(255), unique=True, nullable=False)

    # Booking details
    origin = Column(Text, nullable=False)
    destination = Column(Text, nullable=False)
    move_date = Column(Date, nullable=False)
    distance_km = Column(DECIMAL(10, 2), nullable=False)

    # Lorry and pricing details
    lorry_type = Column(String(50), nullable=False)
    estimated_cost = Column(DECIMAL(10, 2), nullable=False)
    manpower = Column(Integer, nullable=True) 

    # Customer information
    full_name = Column(String(255), nullable=True)
    email = Column(String(255), nullable=False)
    phone = Column(String(50), nullable=True)

    # Additional details
    notes = Column(Text, nullable=True)

    # Timestamps
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    # Relationship to the User model
    user = relationship("User", back_populates="orders")


# ===============================
# Pydantic Model for Input
# ===============================
class OrderCreate(BaseModel):
    user_id: int
    booking_id: str
    origin: str
    destination: str
    move_date: date
    distance_km: float
    lorry_type: str
    estimated_cost: float
    manpower: Optional[int] = None  
    full_name: Optional[str] = None
    email: str
    phone: str
    notes: Optional[str] = None


# ===============================
# Pydantic Model for Response
# ===============================
class OrderResponse(BaseModel):
    id: int
    user_id: int
    booking_id: str
    origin: str
    destination: str
    move_date: date
    distance_km: float
    lorry_type: str
    estimated_cost: float
    manpower: Optional[int] = None  
    full_name: Optional[str] = None
    email: str
    phone: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime
    updated_at: datetime
    lorry_images: Optional[List[str]] = None  # Added for lorry images

    class Config:
        from_attributes = True