from app.extensions import db
from app.models.verification_review import VerificationReview
from app.models.status_history import ApplicationStatusHistory
from datetime import datetime,timezone


def process_verification_review(application_type, application_id, reviewer_id, outcome, notes = ""):

    """
    Records the verification review outcome for an application.
    """
    # Create a new VerificationReview model instance with the provided data
    review = VerificationReview(
        application_type=application_type,
        application_id=application_id,
        reviewer_id=reviewer_id,
        outcome=outcome,    # e.g., 'verified', 'needs_info', 'declined'
        notes=notes,
        reviewed_at=datetime.now(timezone.utc)  # Store current UTC timestamp
    )


    # Add the review to the database session and commit the transaction
    db.session.add(review)
    db.session.commit()


    return review



def update_application_workflow_status(model_instance, new_status, changed_by, reason=""):

    """
    Updates the status of any application (e.g., from 'Submitted' to 'Under Review' or 'Approved') 
    and automatically logs the change in the ApplicationStatusHistory table for complete audit traceability.
    """
    # 1. Get the current status from the model instance (default to 'Unknown' if status attribute doesn't exist)
    old_status=getattr(model_instance,'status','Unknown')

    # 2. Update the model instance with the new status
    model_instance.status=new_status

    # 3. Create a history record in ApplicationStatusHistory for tracking who changed it and why
    history=ApplicationStatusHistory(
        application_type=model_instance.__tablename__,
        application_id=model_instance.id,
        old_status=old_status,
        new_status=new_status,
        changed_by=changed_by,
        reason=reason,
        changed_at=datetime.now(timezone.utc)

    )



    # 4. Add both the history log and changes to the database session and commit
    db.session.add(history)
    db.session.commit()
    
    return model_instance