from flask import Blueprint, jsonify
from flask_jwt_extended import get_jwt_identity

from app.extensions import db
from app.models.status_history import ApplicationStatusHistory
from app.models.support_request import SupportRequest
from app.models.user import User
from app.models.volunteer_application import VolunteerApplication
from app.services.permissions import jwt_roles_required


status_history_bp = Blueprint('status_history', __name__, url_prefix='/api/v1/status-history')


@status_history_bp.route('/<string:application_type>/<int:application_id>', methods=['GET'])
@jwt_roles_required('Admin', 'Verifier')
def get_status_history(application_type, application_id):
    models = {
        'volunteer': VolunteerApplication,
        'support': SupportRequest,
    }
    model = models.get(application_type)
    if model is None:
        return jsonify({'error': 'Invalid application type'}), 400
    application = db.session.get(model, application_id)
    if application is None:
        return jsonify({'error': 'Application not found'}), 404

    user = db.session.get(User, int(get_jwt_identity()))
    if user.role.role_name == 'Verifier' and application.assigned_to != user.id:
        return jsonify({'error': 'Application not found'}), 404
    entries = ApplicationStatusHistory.query.filter_by(
        application_type=application_type,
        application_id=application_id,
    ).order_by(ApplicationStatusHistory.changed_at.desc()).limit(100).all()
    return jsonify({
        'application_id': application_id,
        'history': [{
            'old_status': entry.old_status,
            'new_status': entry.new_status,
            'reason': entry.reason,
            'changed_at': entry.changed_at.isoformat() if entry.changed_at else None,
            'changed_by': entry.changed_by,
        } for entry in entries],
    }), 200
