"""Webhook handlers for Stripe events."""

from fastapi import APIRouter, Request, HTTPException, Header
from typing import Optional
import json
import base64
import hashlib
import hmac
from agenticlypay.stripe_client import StripeClient
from agenticlypay.payments import PaymentProcessor
from agenticlypay.config import config

router = APIRouter()
stripe_client = StripeClient()
payment_processor = PaymentProcessor()


@router.post("/stripe")
async def stripe_webhook(
    request: Request,
    stripe_signature: Optional[str] = Header(None, alias="stripe-signature"),
):
    """Handle Stripe webhook events."""
    if not stripe_signature:
        raise HTTPException(status_code=400, detail="Missing stripe-signature header")

    try:
        payload = await request.body()
        event = stripe_client.construct_webhook_event(
            payload=payload, sig_header=stripe_signature
        )

        # Handle the event
        event_data = event.to_dict()
        result = payment_processor.handle_webhook(event_data)

        return {"success": True, "handled": result.get("handled", False), "result": result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=f"Invalid payload: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/square")
async def square_webhook(
    request: Request,
    x_square_signature: Optional[str] = Header(None, alias="x-square-signature"),
):
    """Handle Square webhook events."""
    try:
        raw_body = await request.body()
        payload = json.loads(raw_body.decode("utf-8"))

        # Verify webhook signature if configured
        signature_key = config.square_webhook_signature_key
        if signature_key and x_square_signature:
            computed_signature = base64.b64encode(
                hmac.new(
                    signature_key.encode("utf-8"),
                    raw_body,
                    hashlib.sha1,
                ).digest()
            ).decode("utf-8")

            if not hmac.compare_digest(computed_signature, x_square_signature):
                raise HTTPException(status_code=401, detail="Invalid Square signature")

        event_type = payload.get("type")
        data = payload.get("data", {})
        payout_object = data.get("object", {})

        if event_type and event_type.startswith("payout."):
            payout_id = payout_object.get("id") or payout_object.get("payout_id")
            new_status = payout_object.get("status")

            if payout_id:
                from google.cloud import firestore

                db = firestore.Client()
                payouts_query = (
                    db.collection("square_payouts")
                    .where("payout_id", "==", str(payout_id))
                    .limit(1)
                    .stream()
                )

                for doc in payouts_query:
                    doc.reference.update(
                        {
                            "status": new_status or doc.to_dict().get("status", "PENDING"),
                            "updated_at": firestore.SERVER_TIMESTAMP,
                        }
                    )
                    break

        return {"success": True, "event_type": event_type, "handled": True}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/test")
async def test_webhook():
    """Test webhook endpoint."""
    return {"status": "webhook endpoint is active"}

