from fastapi import APIRouter, Depends, HTTPException, status
from sqlmodel import Session, select
from sqlalchemy.orm import joinedload
from typing import List
from app.core.database import get_session
from app.models.coupon import Coupon, CouponCreate, CouponUpdate
from app.models.user import User, UserRole
from app.api.deps import get_current_user

router = APIRouter(prefix="/api/coupons", tags=["coupons"])

@router.get("", response_model=List[Coupon])
async def list_coupons(
    *,
    session: Session = Depends(get_session),
    active_only: bool = True
):
    """List all coupons."""
    statement = select(Coupon).options(joinedload(Coupon.business))
    if active_only:
        statement = statement.where(Coupon.is_active)
    
    coupons = session.exec(statement).all()
    return coupons

@router.post("", response_model=Coupon)
async def create_coupon(
    *,
    session: Session = Depends(get_session),
    coupon_in: CouponCreate,
    current_user: User = Depends(get_current_user)
):
    """Create a new coupon (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can create coupons"
        )
    
    db_coupon = Coupon.from_orm(coupon_in)
    session.add(db_coupon)
    session.commit()
    session.refresh(db_coupon)
    return db_coupon

@router.patch("/{coupon_id}", response_model=Coupon)
async def update_coupon(
    *,
    session: Session = Depends(get_session),
    coupon_id: str,
    coupon_in: CouponUpdate,
    current_user: User = Depends(get_current_user)
):
    """Update a coupon (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can update coupons"
        )
    
    db_coupon = session.get(Coupon, coupon_id)
    if not db_coupon:
        raise HTTPException(status_code=404, detail="Coupon not found")
    
    coupon_data = coupon_in.dict(exclude_unset=True)
    for key, value in coupon_data.items():
        setattr(db_coupon, key, value)
    
    session.add(db_coupon)
    session.commit()
    session.refresh(db_coupon)
    return db_coupon

@router.delete("/{coupon_id}")
async def delete_coupon(
    *,
    session: Session = Depends(get_session),
    coupon_id: str,
    current_user: User = Depends(get_current_user)
):
    """Delete a coupon (Promoters and Admins only)."""
    if current_user.role not in [UserRole.ADMIN, UserRole.PROMOTER]:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only promoters and admins can delete coupons"
        )
    
    db_coupon = session.get(Coupon, coupon_id)
    if not db_coupon:
        raise HTTPException(status_code=404, detail="Coupon not found")
    
    session.delete(db_coupon)
    session.commit()
    return {"status": "success", "message": "Coupon deleted"}
