import logging
import paypalrestsdk
from fastapi import HTTPException, APIRouter

from ..supabase.supabase import SupabaseClient
from .payment_handler import PaymentRequest, PaymentHandler

# Set up logging and supabase
logger = logging.getLogger(__name__)
supabase = SupabaseClient()

# Configure PayPal SDK
paypalrestsdk.configure({
    "mode": "sandbox",  # Use 'live' for production
    "client_id": "YOUR_PAYPAL_CLIENT_ID",
    "client_secret": "YOUR_PAYPAL_SECRET"
})


# Define the API router
router = APIRouter()

@router.post("/purchase/credits")
def purchase_credits(payment_request: PaymentRequest):
    """
    Handles token purchases. Calculates the number of tokens based on the amount paid,
    updates the user's balance, and processes PayPal payment.
    """
    payment_handler = PaymentHandler(payment_request)

    # Create PayPal payment and get the approval URL
    approval_url = payment_handler.create_paypal_payment()

    return {
        "message": "Purchase initiated successfully",
        "payment_id": payment_handler.payment_id,
        "credits": payment_request.credit_amount,
        "approval_url": approval_url,
    }


@router.get("/payment/success")
def payment_success(paymentId: str, PayerID: str):
    """
    Handles successful PayPal payment.
    """
    payment = paypalrestsdk.Payment.find(paymentId)

    if payment.execute({"payer_id": PayerID}):
        logger.info("Payment executed successfully")

        # Retrieve transaction details from the database
        result = supabase.table("pending_payments").select("*").eq("payment_id", paymentId).single().execute()
        if not result.data:
            raise HTTPException(status_code=404, detail="Transaction not found")

        # Extract the necessary information
        user_id = result.data["user_id"]
        credit_amount = result.data["credit_amount"]

        # Update the user's balance
        supabase.increment_credit_balance(user_id, amount=credit_amount)

        # Optionally, delete the pending payment entry since the transaction is completed
        supabase.table("pending_payments").delete().eq("payment_id", paymentId).execute()

        return {"message": "Payment completed successfully"}
    else:
        logger.error(f"Payment execution failed: {payment.error}")
        raise HTTPException(status_code=500, detail="Payment execution failed")


@router.get("/payment/cancel")
def payment_cancel():
    """
    Handles PayPal payment cancellation.
    """
    return {"message": "Payment was cancelled"}

