@router.post("/create-checkout-session")
async def create_checkout_session(data: CheckoutRequest):
    try:
        print(data)
        user_email = data.email
        user_name = data.name
        # Check for existing customer
        existing_customers = stripe.Customer.list(email=user_email)
        customer = existing_customers.data[0] if existing_customers.data else stripe.Customer.create(
            email=user_email,
            name=user_name
        )
        metadata = {
            "credit_score": str(data.credit_point),
            "user_id": str(data.user_id),
            "amount": str(data.price),
            "customer_id": customer.id
        }
        if data.plan:
            metadata["plan"] = str(data.plan)


        checkout_session = stripe.checkout.Session.create(
            mode="payment",
            locale="auto",
            invoice_creation={
                "enabled": True
            },
            customer_email=user_email,
            payment_intent_data={
                "description": f"Payment for {data.credit_point} Credit Points",
                "metadata": metadata
            },
            line_items=[{
                "quantity": 1,
                "price_data": {
                    "currency": "usd",
                    "unit_amount": int(data.price * 100),
                    "product_data": {
                        "name": f"Payment for {data.credit_point} Credit Points"
                    }
                }
            }],
            success_url="http://localhost:8000/success?session_id={CHECKOUT_SESSION_ID}",
            cancel_url="http://localhost:8000/cancel"
        )

        return {"checkout_url": checkout_session.url}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))#


@router.post("/webhook")
async def stripe_webhook(
    request: Request,
    stripe_signature: str = Header(None)
):
    payload = await request.body()

    try:
        event = stripe.Webhook.construct_event(
            payload=payload,
            sig_header=stripe_signature,
            secret=STRIPE_WEBHOOK_SECRET
        )
    except stripe.error.SignatureVerificationError:
        raise HTTPException(status_code=400, detail="Invalid Stripe signature")

    print("📦 Event type:", event["type"])
    event_id = event["id"]

    # === 1. Checkout Session Completed ===
    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]

        try:
            invoice_url = None
            invoice_id = session.get("invoice")
            if invoice_id:
                invoice = stripe.Invoice.retrieve(invoice_id)
                invoice_url = invoice.get("hosted_invoice_url")
                print("📄 Invoice URL:", invoice_url)

            payment_intent_id = session.get("payment_intent")
            payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
            metadata = payment_intent.get("metadata", {})

            user_id = int(metadata.get("user_id", 0))
            credit_score = int(metadata.get("credit_score", 0))
            plan = metadata.get("plan")
            amount = int(metadata.get("amount", 0))
            currency = session.get("currency", "usd").lower()
            customer_id = metadata.get("customer_id")
            customer_email = session.get("customer_email", "N/A")
            customer_name = session.get("customer_details", {}).get("name", "N/A")
            checkout_session_id = session.get("id")
            status = "pending"
            created_at = updated_at = datetime.utcnow()

            payment_doc = {
                "user_id": user_id,
                "plan": plan,
                "credit_point": credit_score,
                "amount": amount,
                "transaction_id": payment_intent_id,
                "customer_id": customer_id,
                "checkout_session_id": checkout_session_id,
                "paid_amount_currency": currency,
                "created_at": created_at,
                "updated_at": updated_at,
                "invoice_url": invoice_url,
                "email": customer_email,
                "stripe_event": event_id
            }

            await payments_details_collection.update_one(
                {"transaction_id": payment_intent_id},
                {"$set": payment_doc},
                upsert=True
            )

            print(f"📝 Stored pending checkout for user {user_id}, txn: {payment_intent_id}")

        except Exception as e:
            print(f"❌ Error in checkout.session.completed: {e}")
            raise HTTPException(status_code=500, detail="Failed to process session")

    # === 2. Charge Succeeded ===
    elif event["type"] == "charge.succeeded":

        print(f"📝 Charge succeeded for txn: {event_id}")
        charge = event["data"]["object"]

        try:
            payment_intent_id = charge.get("payment_intent")
            payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
            metadata = payment_intent.get("metadata", {})

            invoice_url = None
            invoice_id = charge.get("invoice")
            if invoice_id:
                invoice = stripe.Invoice.retrieve(invoice_id)
                invoice_url = invoice.get("hosted_invoice_url")

            card = charge.get("payment_method_details", {}).get("card", {})
            card_last4 = card.get("last4", "N/A")
            card_brand = card.get("brand", "N/A")
            card_exp_month = card.get("exp_month", "N/A")
            card_exp_year = card.get("exp_year", "N/A")

            user_id = int(metadata.get("user_id", 0))
            credit_score = int(metadata.get("credit_score", 0))
            plan = metadata.get("plan")
            amount = int(charge.get("amount", 0))
            currency = charge.get("currency", "usd").lower()
            customer_id = charge.get("customer")
            customer_email = metadata.get("customer_email", "N/A")
            checkout_session_id = metadata.get("checkout_session_id", "N/A")
            status = "payment_success"
            created_at = updated_at = datetime.utcnow()

            payment_doc = {
                "user_id": user_id,
                "plan": plan,
                "credit_point": credit_score,
                "amount": amount,
                "transaction_id": payment_intent_id,
                "customer_id": customer_id,
                "checkout_session_id": checkout_session_id,
                "payment_status": status,
                "paid_amount_currency": currency,
                "created_at": created_at,
                "updated_at": updated_at,
                "message": "Payment successful",
                "invoice_url": invoice_url,
                "email": customer_email,
                "card_details": {
                    "last4": card_last4,
                    "brand": card_brand,
                    "exp_month": card_exp_month,
                    "exp_year": card_exp_year
                },
                "stripe_event": event_id
            }

            await payments_details_collection.update_one(
                {"transaction_id": payment_intent_id},
                {"$set": payment_doc},
                upsert=True
            )

            print(f"✅ Payment success stored for {user_id}, amount: {amount/100:.2f} {currency}")

        except Exception as e:
            print(f"❌ Error in charge.succeeded: {e}")
            raise HTTPException(status_code=500, detail="Failed to process charge")

    # === 3. Payment Failed ===
    elif event["type"] == "payment_intent.payment_failed":
        intent = event["data"]["object"]
        metadata = intent.get("metadata", {})
        error_message = intent.get("last_payment_error", {}).get("message", "Unknown error")

        try:
            user_id = int(metadata.get("user_id", 0))
            credit_score = int(metadata.get("credit_score", 0))
            plan = metadata.get("plan")
            amount = int(metadata.get("amount", 0))
            transaction_id = intent["id"]
            created_at = datetime.utcnow()

            failed_doc = {
                "user_id": user_id,
                "plan": plan,
                "credit_point": credit_score,
                "amount": amount,
                "transaction_id": transaction_id,
                "payment_status": "failed",
                "message": error_message,
                "created_at": created_at,
                "stripe_event": event_id
            }

            await payments_details_collection.insert_one(failed_doc)

            print(f"❌ Payment failed: {transaction_id}, reason: {error_message}")

        except Exception as e:
            print(f"❌ Error in payment_intent.payment_failed: {e}")
            raise HTTPException(status_code=500, detail="Failed to process failure")

    return {"status": "ok"}

this is my code and here i want to separate the db logic and write that login in service.py and iport that functin here