
import json
import polar
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from .models import PolarSubscription

polar.api_key = settings.POLAR_API_KEY

@csrf_exempt
def polar_webhook(request):
    if request.method != 'POST':
        return HttpResponse(status=405)

    payload = request.body
    sig_header = request.headers.get('Polar-Signature-256')
    webhook_secret = settings.POLAR_WEBHOOK_SECRET

    try:
        event = polar.webhooks.construct_event(
            payload=payload,
            sig_header=sig_header,
            secret=webhook_secret
        )
    except ValueError as e:
        # Invalid payload
        return HttpResponse(status=400)
    except polar.errors.SignatureVerificationError as e:
        # Invalid signature
        return HttpResponse(status=400)

    # Handle the event
    if event.type == 'subscription.created':
        subscription = event.data
        # Create a new PolarSubscription object
        PolarSubscription.objects.create(
            user_id=subscription['customer_id'], # Assuming customer_id is the user_id
            subscription_id=subscription['id'],
            status=subscription['status'],
            expires_at=subscription['current_period_end'],
        )
    elif event.type == 'subscription.updated':
        subscription = event.data
        # Update the PolarSubscription object
        PolarSubscription.objects.filter(subscription_id=subscription['id']).update(
            status=subscription['status'],
            expires_at=subscription['current_period_end'],
        )
    else:
        print(f'Unhandled event type {event.type}')

    return HttpResponse(status=200)

@login_required
def create_checkout_session(request):
    # Replace with your actual price ID from Polar.sh
    price_id = "REPLACE_WITH_YOUR_PRICE_ID"

    checkout_session = polar.checkout.create(
        price=price_id,
        customer_email=request.user.email,
        success_url="http://localhost:8000/", # Replace with your success URL
    )

    return HttpResponseRedirect(checkout_session.url)
