from decimal import Decimal
import uuid
from django.utils import timezone
from ledgers.ledgers_helper import post_transaction
from organisations.models import Organisation
from customers.models import Customer
from savings.savings_bal_helper import get_account_balance
from .models import MobileMoneySettings


def post_mobile_money_charge(
    member: Customer,
    amount: Decimal,
    transaction_type: str,    # "deposit" or "withdrawal"
    organization: Organisation,
    customer_account,           # required
    created_by=None
):
    """
    Post mobile money charge for a deposit/withdrawal using the SystemTransactions ledger.
    Deducts charge from member's savings account and credits to organization's income account.
    """

    # Get active mobile money settings
    settings = MobileMoneySettings.objects.filter(
        organization=organization,
        setting_type=transaction_type,
        is_active=True
    ).first()

    if not settings or not settings.income_account:
        return {"charge": 0, "message": "No settings or income account — charge skipped"}

    # Calculate the charge
    charge = settings.calculate_charge(amount)
    charge = Decimal(charge).quantize(Decimal("0.01"))

    if charge <= 0:
        return {"charge": 0, "message": "No charge applicable"}
    
    member_chart = customer_account.account_product.accounts_chart

    current_balance = get_account_balance(customer_account)['balance_raw']

    if float(current_balance) < float(charge):
        raise Exception(f"Insufficient balance to deduct charge of {charge}. Current balance: {current_balance}")

    branch = customer_account.customer_branch
    now = timezone.now()

    # Prepare details for post_transaction helper
    # The post_transaction will handle the ledger entry with debit from member_chart and credit to income_account
    transaction_type_heading = f"MM Deposit Charge: {member.name}" if transaction_type else f"MM withdrawal Charge: {member.name}"
    transaction_details = {
        "heading": transaction_type_heading,
        "amount": float(charge),
        "record_date": now,
        "debit_chart_id": member_chart.id,               # Deduct from member's savings account
        "credit_chart_id": settings.income_account.id,   # Credit org income account
        "payment_method": "mobile_money",
        "voucher_no": None,
        "ref_no_prefix": "inc",
        "organisation_id": organization.id,
        "branch_id": branch.id,
        "user_id": created_by.id if created_by else None
    }

    charge_transaction = post_transaction(transaction_details)

    new_balance = float(current_balance) - float(charge)

    return {
        "charge": float(charge),
        "charge_transaction_id": charge_transaction.id,
        "wallet_balance": float(new_balance),
        "status": "charge_posted"
    }
