from fastapi import APIRouter, BackgroundTasks, Depends, Query, status
from sqlalchemy.orm import Session

from .. import crud, schemas, security
from ..database import get_db
from ..email_service import send_sponsorship_emails

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


@router.post("", response_model=schemas.SponsorshipOut, status_code=status.HTTP_201_CREATED)
def create_sponsorship(
    payload: schemas.SponsorshipCreate,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
) -> schemas.SponsorshipOut:
    sponsorship = crud.create_sponsorship_request(db, payload)
    background_tasks.add_task(
        send_sponsorship_emails,
        company=payload.company,
        contact_name=payload.contact_name,
        tier=payload.tier,
        email=payload.email,
        phone=payload.phone,
        message=payload.message,
    )
    return sponsorship


@router.get(
    "",
    response_model=list[schemas.SponsorshipOut],
    dependencies=[Depends(security.require_roles(*security.VIEW_ROLES))],
)
def list_sponsorships(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=500),
    db: Session = Depends(get_db),
) -> list[schemas.SponsorshipOut]:
    return crud.list_sponsorship_requests(db, skip=skip, limit=limit)
