from sqlmodel import SQLModel, Field, Column, Relationship
from datetime import datetime
from typing import Optional, TYPE_CHECKING
from uuid import UUID, uuid4
from sqlalchemy import DateTime, func

if TYPE_CHECKING:
    from app.models.business import Business

class Coupon(SQLModel, table=True):
    """Coupon record for promotions."""
    
    __tablename__ = "coupons"
    
    id: Optional[UUID] = Field(default_factory=uuid4, primary_key=True)
    business_id: Optional[UUID] = Field(default=None, foreign_key="businesses.id")
    title: str = Field(index=True)
    description: Optional[str] = None
    
    # Relationship to business
    business: Optional["Business"] = Relationship(back_populates="coupons")
    business_name: Optional[str] = None
    business_address: Optional[str] = None
    business_phone: Optional[str] = None
    image_url: Optional[str] = None
    social_media: Optional[str] = None
    terms: Optional[str] = None
    discount_percentage: Optional[int] = None
    discount_amount: Optional[float] = None
    category: Optional[str] = None
    valid_from: Optional[datetime] = Field(
        sa_column=Column(DateTime(timezone=True), nullable=True)
    )
    valid_until: Optional[datetime] = Field(
        sa_column=Column(DateTime(timezone=True), nullable=True)
    )
    is_active: bool = Field(default=True)
    created_at: Optional[datetime] = Field(
        default=None,
        sa_column=Column(DateTime(timezone=True), server_default=func.now())
    )
    updated_at: Optional[datetime] = Field(
        default=None,
        sa_column=Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    )

class CouponCreate(SQLModel):
    title: str
    business_id: Optional[UUID] = None
    description: Optional[str] = None
    business_name: Optional[str] = None
    business_address: Optional[str] = None
    business_phone: Optional[str] = None
    image_url: Optional[str] = None
    social_media: Optional[str] = None
    terms: Optional[str] = None
    discount_percentage: Optional[int] = None
    discount_amount: Optional[float] = None
    category: Optional[str] = None
    valid_from: Optional[datetime] = None
    valid_until: Optional[datetime] = None
    is_active: Optional[bool] = True

class CouponUpdate(SQLModel):
    title: Optional[str] = None
    business_id: Optional[UUID] = None
    description: Optional[str] = None
    business_name: Optional[str] = None
    business_address: Optional[str] = None
    business_phone: Optional[str] = None
    image_url: Optional[str] = None
    social_media: Optional[str] = None
    terms: Optional[str] = None
    discount_percentage: Optional[int] = None
    discount_amount: Optional[float] = None
    category: Optional[str] = None
    valid_from: Optional[datetime] = None
    valid_until: Optional[datetime] = None
    is_active: Optional[bool] = None
