# views.py
import stripe
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
import json
import logging
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from django.http import HttpResponse
stripe.api_key = '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'

logger = logging.getLogger(__name__)

class CreatePaymentIntentView(APIView):
    def post(self, request):
        try:
            # Get amount and currency from frontend (in cents!)
            amount = request.data.get('amount')  # e.g., 2000 = $20.00
            currency = request.data.get('currency', 'usd')
            payment_method_id = request.data.get('payment_method_id')

            if not amount or not payment_method_id:
                return Response(
                    {'error': 'Missing amount or payment_method_id'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            customer = stripe.Customer.create(
                payment_method=payment_method_id,
                email=request.data.get('email', ''),
                invoice_settings={'default_payment_method': payment_method_id}
            )

            intent = stripe.PaymentIntent.create(
                amount=amount,
                currency=currency,
                customer=customer.id,
                payment_method=payment_method_id,
                off_session=True,  
                confirm=True,     
                return_url="https://your-frontend.com/success/",  
            )

            if intent.status == 'succeeded':
                return Response({
                    'message': 'Payment succeeded!',
                    'payment_intent_id': intent.id
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    'error': 'Payment not confirmed',
                    'status': intent.status
                }, status=status.HTTP_400_BAD_REQUEST)

        except stripe.error.CardError as e:
            return Response({'error': str(e.user_message)}, status=status.HTTP_400_BAD_REQUEST)
        except stripe.error.StripeError as e:
            return Response({'error': 'Stripe error: ' + str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except Exception as e:
            return Response({'error': 'Internal server error: ' + str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        






class CreateCheckoutSessionView(APIView):
    
    def post(self, request):
        try:
            product_name = request.data.get('product_name', 'One-time purchase')
            amount = request.data.get('amount')  # in cents
            currency = request.data.get('currency', 'usd')

            if not amount or amount <= 0:
                return Response(
                    {'error': 'Valid amount (in cents) is required'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # # Optional: Save order in pending state
            # order = Order.objects.create(
            #     product_name=product_name,
            #     amount=amount,
            #     currency=currency,
            #     paid=False
            # )

            checkout_session = stripe.checkout.Session.create(
                payment_method_types=['card'],
                line_items=[{
                    'price_data': {
                        'currency': currency,
                        'product_data': {'name': product_name},
                        'unit_amount': amount,
                    },
                    'quantity': 1,
                }],
                mode='payment',
                success_url='https://your-frontend.com/success?session_id={CHECKOUT_SESSION_ID}',
                cancel_url='https://your-frontend.com/cancel',
                metadata={'order_id': "order.id"},  # Link to your DB
            )

            # # Save session ID for later reference
            # order.stripe_checkout_session_id = checkout_session.id
            # order.save()

            return Response({'url': checkout_session.url})

        except Exception as e:
            logger.error(f"Checkout error: {str(e)}")
            return Response(
                {'error': 'Failed to create checkout session'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


@csrf_exempt
def stripe_webhook(request):
    """
    Handle Stripe webhooks (e.g., payment success)
    Register this endpoint in Stripe Dashboard: https://dashboard.stripe.com/webhooks
    """
    payload = request.body
    sig_header = request.META.get('HTTP_STRIPE_SIGNATURE')
    endpoint_secret = ""

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, endpoint_secret
        )
    except ValueError:
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError:
        return HttpResponse(status=400)

    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        order_id = session['metadata'].get('order_id')

        if order_id:
            try:
                print(f"Order ID: {order_id}")
            #     order = Order.objects.get(id=order_id)
            #     order.paid = True
            #     order.save()
            #     logger.info(f"Order {order_id} marked as paid.")
            except Exception as e:
                logger.warning(f"Error updating order {order_id}: {str(e)}")

    return HttpResponse(status=200)