from decimal import Decimal
from django.utils import timezone
from .razorpay_service import create_order, verify_payment_signature
from apps.payments.models import PaymentTransaction
from apps.core.events.event_bus import emit_event


def create_payment(amount, currency='INR', user=None):
    # Business logic for creating a payment order and transaction
    order = create_order(amount, currency=currency)
    txn = PaymentTransaction.objects.create(
        user=user,
        provider='razorpay',
        provider_order_id=order.get('id'),
        amount=Decimal(amount),
        currency=currency,
        status='created',
    )
    return {'order': order, 'transaction_id': str(txn.id)}


def verify_payment(payment_id, order_id, signature, transaction_id):
    # Verify signature and update transaction status
    verify_payment_signature(payment_id, order_id, signature)
    txn = PaymentTransaction.objects.get(id=transaction_id)
    txn.provider_payment_id = payment_id
    txn.status = 'success'
    txn.completed_at = timezone.now()
    txn.save(update_fields=['provider_payment_id', 'status', 'completed_at'])
    emit_event('payment_success', {'payment_id': str(txn.id), 'order_id': order_id})
    return txn


def refund_payment(transaction_id, amount=None):
    # placeholder for refund logic across providers
    txn = PaymentTransaction.objects.get(id=transaction_id)
    # provider-specific refund calls would go here
    txn.status = 'refunded'
    txn.save(update_fields=['status'])
    emit_event('payment_refunded', {'payment_id': str(txn.id)})
    return txn
