from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, validator, Field

class ShippingDetails(BaseModel):
    name: str
    address: str
    city: str
    postal_code: str
    country: str
    phone: str

class OrderItemBase(BaseModel):
    product_id: int
    quantity: int

class OrderItemCreate(OrderItemBase):
    pass

class OrderItemResponse(OrderItemBase):
    id: int
    order_id: int
    points_per_item: int
    total_points: int
    created_at: datetime
    product_name: Optional[str] = None
    product_image: Optional[str] = None
    product_price: Optional[int] = None

    class Config:
        orm_mode = True

class OrderBase(BaseModel):
    address_id: Optional[int] = None
    shipping_details: Optional[ShippingDetails] = None
    save_address: Optional[bool] = False
    address_title: Optional[str] = None

    @validator('shipping_details', 'address_id')
    def check_shipping_info(cls, v, values):
        # 주소 ID와 배송 정보 중 하나는 반드시 제공되어야 함
        if 'address_id' in values and values['address_id'] is None and v is None:
            raise ValueError('Either address_id or shipping_details must be provided')
        return v
    
    @validator('address_title')
    def validate_address_title(cls, v, values):
        # 주소 저장 옵션이 True이고 shipping_details가 제공된 경우에만 address_title 필요
        if values.get('save_address') and values.get('shipping_details') and not v:
            raise ValueError('address_title is required when save_address is True')
        return v

class OrderCreate(OrderBase):
    """Request model for creating a new order from cart"""
    pass

class OrderResponse(OrderBase):
    id: int
    user_id: int
    order_number: str
    total_points: int
    status: str
    items: List[OrderItemResponse] = []
    created_at: datetime
    updated_at: datetime

    class Config:
        orm_mode = True

# 주문 요약 정보를 위한 스키마
class OrderSummary(BaseModel):
    unique_users_count: int  # 주문한 고유 사용자 수
    order_count: int  # 총 주문 건수
    total_points: int  # 총 사용 포인트
    start_date: datetime  # 집계 시작 날짜
    end_date: datetime  # 집계 종료 날짜 