"""
One place for "validate the loan form and save it" so Add Loan and Edit Loan
behave the same in the admin and staff panels.

    errors, data = validate_loan_form(request, place_resolver)
    loan = save_loan(data, staff=..., loan=None)      # create
    loan = save_loan(data, loan=existing)             # update
"""
import re

from django.db import transaction
from django.db.models import Sum

from NexusApp.models import Customer, Loan, Place
from controllers.Admin.AddLoanController import (
    MAX_NOTES, MAX_PLACE, TOTAL_LIMIT,
    _customer_form_data, _parse_date, _parse_money, _validate_customer,
)


def admin_place_resolver(name):
    """Place must be one of the places added in Add Place."""
    place = Place.objects.filter(name__iexact=name).first()
    if place is None:
        return None, "Select a place from the list (add new places in Loan Registers)."
    return place, None


def make_staff_place_resolver(staff_places_qs):
    def resolve(name):
        place = staff_places_qs.filter(name__iexact=name).first()
        if place is None:
            return None, "You can only add loans for your assigned locations."
        return place, None
    return resolve


def validate_loan_form(request, place_resolver, existing_loan=None):
    post = request.POST
    customer_data = _customer_form_data(request)
    photo = request.FILES.get('aadhaar_photo')
    errors = _validate_customer(customer_data, photo, referral_required=existing_loan is None)

    place_name = ' '.join(post.get('place', '').split())
    place = None
    if not place_name:
        errors['place'] = "Select a place."
    elif len(place_name) > MAX_PLACE:
        errors['place'] = f"Place cannot exceed {MAX_PLACE} characters."
    else:
        place, err = place_resolver(place_name)
        if err:
            errors['place'] = err

    loan_date = _parse_date(post.get('loan_date', '').strip())
    if not post.get('loan_date', '').strip():
        errors['loan_date'] = "Loan date is required."
    elif not loan_date:
        errors['loan_date'] = "Invalid date format (use YYYY-MM-DD)."

    amount = None
    raw = post.get('loan_amount', '').strip()
    if not raw:
        errors['loan_amount'] = "Loan amount is required."
    else:
        amount = _parse_money(raw)
        if amount is None:
            errors['loan_amount'] = "Enter a valid positive loan amount (max 2 decimals)."

    payment_type = post.get('payment_type', '').strip()
    if not payment_type:
        errors['payment_type'] = "Payment type is required."
    elif payment_type not in dict(Loan.PAYMENT_TYPE_CHOICES):
        errors['payment_type'] = "Select a valid payment type."

    first_due = _parse_date(post.get('first_due_date', '').strip())
    if not post.get('first_due_date', '').strip():
        errors['first_due_date'] = "First due date is required."
    elif not first_due:
        errors['first_due_date'] = "Invalid date format (use YYYY-MM-DD)."
    elif loan_date and first_due < loan_date:
        errors['first_due_date'] = "First due date cannot be before the loan date."
    elif first_due.weekday() == 6:
        errors['first_due_date'] = "First due date cannot be a Sunday (no dues on Sundays)."

    dues = None
    raw = post.get('number_of_dues', '').strip()
    if not raw:
        errors['number_of_dues'] = "Number of dues is required."
    elif not re.fullmatch(r'[0-9]{1,9}', raw) or int(raw) <= 0:
        errors['number_of_dues'] = "Enter a valid number of dues."
    else:
        dues = int(raw)

    per_due = None
    raw = post.get('due_amount', '').strip()
    if not raw:
        errors['due_amount'] = "Due amount is required."
    else:
        per_due = _parse_money(raw)
        if per_due is None:
            errors['due_amount'] = "Enter a valid positive due amount."

    if per_due is not None and dues is not None:
        total = per_due * dues
        if total >= TOTAL_LIMIT:
            errors['number_of_dues'] = "Total payable is too large for the given due amount."
        elif existing_loan is not None:
            paid = existing_loan.payments.aggregate(s=Sum('amount'))['s'] or 0
            if total < paid:
                errors['number_of_dues'] = (
                    f"Total payable (₹{total:,.2f}) cannot be less than the amount "
                    f"already paid (₹{paid:,.2f})."
                )

    notes = post.get('notes', '').strip()
    if not notes:
        errors['notes'] = "Notes are required."
    elif len(notes) > MAX_NOTES:
        errors['notes'] = f"Notes cannot exceed {MAX_NOTES} characters."

    # Aadhaar must stay unique: editing a loan cannot steal another customer's Aadhaar
    if existing_loan is not None and 'aadhaar_number' not in errors and Customer.objects.filter(
            aadhaar_number=customer_data['aadhaar_number']
    ).exclude(pk=existing_loan.customer_id).exists():
        errors['aadhaar_number'] = "This Aadhaar number belongs to another customer."

    return errors, {
        'customer': customer_data, 'photo': photo, 'place': place,
        'loan_date': loan_date, 'loan_amount': amount, 'payment_type': payment_type,
        'first_due_date': first_due, 'number_of_dues': dues, 'due_amount': per_due,
        'notes': notes,
    }


@transaction.atomic
def save_loan(data, staff=None, loan=None):
    place = data['place']
    if place.pk is None:
        place, _ = Place.objects.get_or_create(name=place.name)

    c = data['customer']
    if loan is None:
        customer = Customer.objects.select_for_update().filter(
            aadhaar_number=c['aadhaar_number']).first() or Customer(aadhaar_number=c['aadhaar_number'])
    else:
        customer = Customer.objects.select_for_update().get(pk=loan.customer_id)
        customer.aadhaar_number = c['aadhaar_number']

    customer.customer_name = c['customer_name']
    customer.phone_number = c['phone_number']
    customer.address = c['address']
    customer.referral_name = c['referral_name'] or None
    customer.referral_phone = c['referral_phone'] or None
    if data['photo']:
        customer.aadhaar_photo = data['photo']
    customer.save()

    if loan is None:
        loan = Loan(customer=customer, staff=staff)
    loan.place = place
    loan.loan_date = data['loan_date']
    loan.loan_amount = data['loan_amount']
    loan.payment_type = data['payment_type']
    loan.first_due_date = data['first_due_date']
    loan.number_of_dues = data['number_of_dues']
    loan.due_amount = data['due_amount']
    loan.notes = data['notes']
    loan.save()                                   # recalculates total_payable

    # status follows the money: fully paid -> completed, otherwise active
    if loan.pk:
        paid = loan.payments.aggregate(s=Sum('amount'))['s'] or 0
        if paid >= loan.total_payable and loan.status != 'completed':
            last = loan.payments.order_by('-payment_date').first()
            loan.status, loan.closed_date = 'completed', last.payment_date if last else None
            loan.save(update_fields=['status', 'closed_date', 'updated_at'])
        elif paid < loan.total_payable and loan.status == 'completed':
            loan.status, loan.closed_date = 'active', None
            loan.save(update_fields=['status', 'closed_date', 'updated_at'])
    return loan


def loan_form_initial(loan):
    """Values used to pre-fill the loan form in edit mode."""
    cu = loan.customer
    return {
        'phone_number': cu.phone_number, 'place': loan.place.name,
        'customer_name': cu.customer_name, 'address': cu.address,
        'aadhaar_number': cu.aadhaar_number, 'referral_name': cu.referral_name or '',
        'referral_phone': cu.referral_phone or '',
        'loan_date': loan.loan_date.isoformat(), 'loan_amount': str(loan.loan_amount),
        'payment_type': loan.payment_type, 'first_due_date': loan.first_due_date.isoformat(),
        'number_of_dues': str(loan.number_of_dues), 'due_amount': str(loan.due_amount),
        'notes': loan.notes or '',
        'aadhaar_photo_url': cu.aadhaar_photo.url if cu.aadhaar_photo else '',
    }
