# Brad ran this on 2025-03-08 @ 11pm ET to cancel pending refunds and re-initiate them for all Visa charges

# The main issue was that we had initiated ~25k refunds earlier in the day that were still pending

# This script cancels pending refunds and re-initiates them.

# It is unclear if the API command to cancel a Refund ever works. It did not successfully cancel any pending refunds

import os
import pandas as pd

import stripe

stripe.api_key = os.getenv("STRIPE_API_KEY")

all_charges = pd.read_csv("Run_history-2025-03-08-21-39-00.csv") # csv that Martin assembled
visa_charges = all_charges[all_charges['card_brand'] == 'Visa']

# For testing
# Take only the first 10 Visa charges
# visa_charges = visa_charges.head(10)

print(visa_charges)

pending_refund_counter = 0
refunded_counter = 0
error_counter = 0
new_refund_counter = 0

starttime = time.time()

for charge_id in visa_charges['charge_id']:
    charge = stripe.Charge.retrieve(
        charge_id,
        expand=['refunds']
    )

    if charge.refunds.data:
        for refund in charge.refunds.data:
            if refund.status == 'pending':
                try:
                    stripe.Refund.cancel(refund.id)
                    print(f"Cancelling pending refund for charge {charge.id} [{pending_refund_counter} Total]")
                    pending_refund_counter += 1
                    # Create a new refund for the charge after cancelling the pending one
                    new_refund = stripe.Refund.create(
                        charge=charge.id,
                        amount=charge.amount  # Refund the full amount
                    )
                    print(f"Created new refund {new_refund.id} for charge {charge.id} [{new_refund_counter} Total]")
                    new_refund_counter += 1
                except Exception as e:
                    print(f"Unable to cancel pending refund {charge.id}: {e} {error_counter} total errors")
                    error_counter += 1
            if refund.status == 'succeeded':
                print(f"Refund {refund.id} for charge {charge.id} succeeded [{refunded_counter} Total]")
                refunded_counter += 1
    else:
        print(f"No pending refunds for charge {charge.id}")
        refunded_counter += 1

endtime = time.time()

print(f"Total time: {endtime - starttime} seconds")
print("--------------------------------")
print(f"Pending refunds: {pending_refund_counter}")
print(f"Refunded: {refunded_counter}")
print(f"Errors: {error_counter}")
print(f"New refunds: {new_refund_counter}")
