from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from app.models.advertisement import Advertisement
from app.api.deps import get_db, get_current_user
from app.schemas.advertisement import AdvertisementResponse
from app.models.point_transaction import PointTransaction
from app.models.user_points import UserPoints
from app.models.user import User
from app.schemas.advertisement_click import AdvertisementClickRequest
from app.core.time import now
from app.services.advertisement_service import process_advertisement_click

router = APIRouter()

@router.get("/", response_model=List[AdvertisementResponse])
def get_advertisements(db: Session = Depends(get_db)):
    """
    광고 데이터를 조회하여 프론트엔드에 반환합니다.
    반환 항목: id, 광고 URL, 광고가 게시될 순서, 광고에 해당하는 포인트.
    """
    # video_list_order 순(오름차순)으로 정렬하여 광고 데이터 목록을 조회합니다.
    ads = db.query(Advertisement).order_by(Advertisement.video_list_order).all()
    return ads

@router.post("/click")
def advertisement_click(
    req: AdvertisementClickRequest,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    광고 클릭 시 실행되어, 포인트 지급 및 사용자 포인트 업데이트를 진행합니다.
    """
    try:
        result = process_advertisement_click(db, current_user.id, req.ad_id)
        return result
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
