import random
import string
from app.extensions import db
from app.models.status_history import ApplicationStatusHistory

def generate_reference_number(prefix="NGO"):
    """Generates a unique reference number for applications (e.g., NGO-AB123XYZ)"""
    suffix = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
    return f"{prefix}-{suffix}"

def log_status_change(entity_type, entity_id, old_status, new_status, changed_by, reason=""):
    """Records application status changes in the history table for traceability."""
    history = ApplicationStatusHistory(
        application_type=entity_type,
        application_id=entity_id,
        old_status=old_status,
        new_status=new_status,
        changed_by=changed_by,
        reason=reason
    )
    db.session.add(history)
    db.session.commit()