import requests
from decimal import Decimal
from django.core.management.base import BaseCommand
from django.conf import settings
from alumni.models import Donation
from alumni.utils import log_system_event   # adjust if location differs


class Command(BaseCommand):
    help = "Reconcile pending donations with Paystack"

    def handle(self, *args, **kwargs):

        pending_donations = Donation.objects.filter(status="PENDING")

        if not pending_donations.exists():
            self.stdout.write(self.style.SUCCESS("No pending donations found."))
            return

        for donation in pending_donations:
            reference = donation.reference
            url = f"https://api.paystack.co/transaction/verify/{reference}"

            headers = {
                "Authorization": f"Bearer {settings.PAYSTACK_SECRET_KEY}",
            }

            try:
                response = requests.get(url, headers=headers, timeout=60)
                response_data = response.json()

                if response_data.get("status") and response_data["data"]["status"] == "success":

                    paystack_data = response_data["data"]
                    paystack_amount = Decimal(paystack_data["amount"]) / Decimal("100")

                    if paystack_amount == donation.amount:

                        donation.status = "SUCCESS"
                        donation.transaction_id = paystack_data.get("id")
                        donation.payment_channel = paystack_data.get("channel")
                        donation.gateway_response = paystack_data.get("gateway_response")
                        donation.paid_at = paystack_data.get("paid_at")
                        donation.save()

                        log_system_event(
                            user=donation.user,
                            action_type="CRON_DONATION_VERIFIED",
                            description=f"Cron verified donation. Ref: {reference}",
                            request=None
                        )

                        self.stdout.write(self.style.SUCCESS(
                            f"Donation verified: {reference}"
                        ))

                    else:
                        donation.status = "FAILED"
                        donation.save()

                        log_system_event(
                            user=donation.user,
                            action_type="CRON_AMOUNT_MISMATCH",
                            description=f"Amount mismatch during cron verification. Ref: {reference}",
                            request=None
                        )

                elif response_data.get("status"):

                    # Transaction found but not successful
                    donation.status = "FAILED"
                    donation.save()

                    log_system_event(
                        user=donation.user,
                        action_type="CRON_DONATION_FAILED",
                        description=f"Cron marked donation as failed. Ref: {reference}",
                        request=None
                    )

                else:
                    log_system_event(
                        user=donation.user,
                        action_type="CRON_VERIFICATION_ERROR",
                        description=f"Verification error: {response_data} | Ref: {reference}",
                        request=None
                    )

            except Exception as e:
                log_system_event(
                    user=donation.user,
                    action_type="CRON_VERIFY_EXCEPTION",
                    description=f"Exception during cron verification: {str(e)} | Ref: {reference}",
                    request=None
                )

        self.stdout.write(self.style.SUCCESS("Reconciliation completed."))