"""Contact form router."""
from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.contact import Contact
from app.schemas.contact import ContactCreate, ContactResponse
from app.services.email_service import EmailService
from app.cache import cache

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


@router.post("", response_model=ContactResponse)
async def create_contact(
    payload: ContactCreate,
    request: Request,
    db: AsyncSession = Depends(get_db),
) -> ContactResponse:
    """Save contact form and send email."""
    client_ip = request.client.host if request.client else "unknown"
    rate_key = f"rate:contact:{client_ip}"
    count = await cache.incr_rate(rate_key, window=60)
    if count > 5:
        raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="Too many requests")

    contact = Contact(
        name=payload.name,
        email=str(payload.email),
        phone=payload.phone,
        message=payload.message,
        privacy_consent=payload.privacy_consent,
    )
    db.add(contact)
    await db.commit()

    email_service = EmailService()
    try:
        sent = await email_service.send_contact_email({
            "name": payload.name,
            "email": str(payload.email),
            "phone": payload.phone,
            "message": payload.message,
        }, db=db)
        if sent:
            contact.email_sent = True
            await db.commit()
    except Exception:
        pass

    return ContactResponse(success=True)
