from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
import stripe
import os
from dotenv import load_dotenv
from stripe.error import SignatureVerificationError

load_dotenv()

STRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY')
STRIPE_ENDPOINT_SECRET = os.getenv('STRIPE_ENDPOINT_SECRET')
stripe.api_key = STRIPE_SECRET_KEY
MY_APP_DOMAIN = os.getenv('MY_APP_DOMAIN')
# Initialize Stripe with your secret key

#Creating stripe Subscription
async def create_checkout_session(account_id: str, account_name: str, email: str, subscription_id: str, subscription_type_id: int, stripe_price_id: str, quantity: int, log_id: str) -> dict:
    try:

        existing_customers = stripe.Customer.list(email=email).data
        if existing_customers:
            customer_id = existing_customers[0].id
        else:
            # Create a new customer with the name
            customer = stripe.Customer.create(email=email, name=account_name)
            customer_id = customer.id

        checkout_session = stripe.checkout.Session.create(
            success_url=f"{MY_APP_DOMAIN}/billing/success?session_id={{CHECKOUT_SESSION_ID}}&subscription_id={subscription_id}",
            cancel_url=f"{MY_APP_DOMAIN}/billing/cancel",
            payment_method_types=["card", "us_bank_account"],  # Including ACH payments
            mode="subscription",
            #customer_email=email,
            customer=customer_id,
            allow_promotion_codes=True,
            line_items=[{
                'price': stripe_price_id,
                'quantity': quantity,
            }],
            metadata={
                "account_id": account_id,
                "subscription_id": subscription_id,
                "subscription_type_id": subscription_type_id,
                "account_name": account_name,
                'quantity': quantity,
                "email": email,
                "log_id": log_id,
            },
        )
        return {"url": checkout_session.url}
    except Exception as e:
        print(f"Stripe session creation failed: {e}")
        return {"error": str(e)}

#Updating Stripe Subscription
async def update_stripe_subscription(subscription_id: str, new_price_id: str, new_quantity: int):
    try:
        subscription = stripe.Subscription.retrieve(subscription_id)
        # Assuming there's only one item in the subscription
        stripe.Subscription.modify(
            subscription_id,
            items=[{
                'id': subscription['items']['data'][0].id,
                'price': new_price_id,
                'quantity': new_quantity,
            }]
        )
        return True
    except stripe.error.StripeError as e:
        return False
        raise HTTPException(status_code=400, detail=str(e.user_message))

async def verify_stripe_signature(request: Request):
    payload = await request.body()
    sig_header = request.headers.get('Stripe-Signature')

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, STRIPE_ENDPOINT_SECRET
        )
        return event
    except ValueError as e:
        # Invalid payload
        raise HTTPException(status_code=400, detail="Invalid payload")
    except SignatureVerificationError as e:
        # Invalid signature
        raise HTTPException(status_code=400, detail="Invalid signature")

