from __future__ import annotations

from typing import Optional
from urllib.parse import urlencode

from fastapi import APIRouter, Query
from fastapi.responses import HTMLResponse, RedirectResponse

router = APIRouter(prefix="/outreach", tags=["Outreach OAuth"])

LOCAL_CALLBACK = "http://localhost:8484/callback"


@router.get("/callback")
async def outreach_cli_callback(
    code: Optional[str] = Query(None),
    state: Optional[str] = Query(None),
    error: Optional[str] = Query(None),
    error_description: Optional[str] = Query(None),
):
    """Bridge HTTPS OAuth callback to local g-gremlin listener."""
    if not code and not error:
        return HTMLResponse(
            """
            <!DOCTYPE html>
            <html>
            <head><title>Outreach OAuth</title></head>
            <body style="font-family: sans-serif; text-align: center; padding: 40px;">
                <h2>Outreach OAuth Callback Error</h2>
                <p>Missing OAuth code or error details.</p>
                <p>You can close this window and retry the authorization.</p>
            </body>
            </html>
            """,
            status_code=400,
        )

    params = {}
    if code:
        params["code"] = code
    if state:
        params["state"] = state
    if error:
        params["error"] = error
    if error_description:
        params["error_description"] = error_description

    target = LOCAL_CALLBACK
    if params:
        target = f"{LOCAL_CALLBACK}?{urlencode(params)}"
    return RedirectResponse(url=target, status_code=302)
