from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from app.schemas import ContactCreate
from app.crud import create_contact
from app.services.email import send_contact_email
from app.config import get_settings
import httpx

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")

@router.get("/contact", response_class=HTMLResponse)
async def contact_page(request: Request):
    settings = get_settings()
    return templates.TemplateResponse("contact.html", {
        "request": request,
        "recaptcha_site_key": settings.recaptcha_site_key
    })

@router.post("/contact")
async def submit_contact(contact_data: ContactCreate):
    # Verify reCAPTCHA
    settings = get_settings()
    recaptcha_secret = settings.recaptcha_secret

    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "https://www.google.com/recaptcha/api/siteverify",
            data={
                "secret": recaptcha_secret,
                "response": contact_data.recaptcha_token
            }
        )
        result = resp.json()
        if not result.get("success"):
            raise HTTPException(status_code=400, detail="Vérification reCAPTCHA échouée")

    # Save to database
    from app.database import get_db
    db_gen = get_db()
    db = await anext(db_gen)
    try:
        await create_contact(db, contact_data)
    finally:
        await db.close()

    # Send email (async, ignore errors)
    try:
        await send_contact_email(
            name=contact_data.name,
            email=contact_data.email,
            subject=contact_data.subject,
            message=contact_data.message
        )
    except Exception as e:
        print(f"Email send failed: {e}")

    return JSONResponse({"success": True, "message": "Message envoyé avec succès"})
