from app.extensions import db 
from app.models.donation import Donation
from datetime import datetime, timezone


def record_donation_transaction(reference_no, amount, currency, method, donor_name, donor_email, gateway=None, transaction_id=None):
    """
    Records a new donation transaction with a pending or initial state.
    """
    # Create a new Donation model instance with transaction details
    donation = Donation(
        transaction_id=reference_no,
        amount=amount,
        currency=currency,
        payment_method=method,
        donor_name=donor_name,   # Pass donor name here
        donor_email=donor_email, # Pass donor email here
        status="pending_verification",
        donated_at=datetime.now(timezone.utc)
    )
    
    # Add to the database session and commit the transaction
    db.session.add(donation)
    db.session.commit()
    
    return donation


def reconcile_donation_payment(donation_id, gateway_transaction_id, status, finance_notes=""):
    """
    Reconciles a donation record after verifying the signed payment gateway callback.
    Updates the payment status to 'matched', 'failed', or 'refunded'.
    """
    # 1. Fetch the donation record by its ID from the database
    donation = Donation.query.get(donation_id)
    
    if not donation:
        raise ValueError("Donation record not found.")
    
    # 2. Update donation status and gateway transaction details
    donation.status = status  # e.g., 'matched', 'failed', 'refunded'
    donation.transaction_id = gateway_transaction_id
    
    # 3. Commit the changes to the database
    db.session.commit()
    
    return donation