from flask import Blueprint, jsonify, request, current_app
from flask_login import current_user, login_required
from app.models import Contract
from app.extensions import db
from datetime import datetime

contract_dispute_bp = Blueprint('contract_dispute', __name__)

@contract_dispute_bp.route('/contracts/<int:contract_id>/agree-resolve', methods=['POST'])
@login_required
def agree_to_resolve(contract_id):
    """Handle mutual dispute resolution agreement"""
    contract = Contract.query.get_or_404(contract_id)
    
    # Check if user is part of this contract
    if current_user.id not in [contract.contractor_id, contract.worker_id]:
        return jsonify({
            "error": "You are not authorized to access this contract"
        }), 403

    # Check if contract is in disputed state
    if contract.status != 'disputed':
        return jsonify({
            "error": "Contract must be in disputed state to agree to resolution"
        }), 400

    try:
        # Set the appropriate flag based on user role
        if current_user.id == contract.worker_id:
            contract.worker_agreed_resolve = True
        else:
            contract.contractor_agreed_resolve = True

        # If both parties have agreed, resolve the dispute
        if contract.worker_agreed_resolve and contract.contractor_agreed_resolve:
            contract.status = 'pending_rating'
            # Reset resolution flags for potential future disputes
            contract.worker_agreed_resolve = False
            contract.contractor_agreed_resolve = False
            message = "Dispute resolved! Ready for final ratings."
        else:
            message = "Agreement recorded. Waiting for other party."

        db.session.commit()

        return jsonify({
            "success": True,
            "message": message,
            "status": contract.status,
            "worker_agreed": contract.worker_agreed_resolve,
            "contractor_agreed": contract.contractor_agreed_resolve
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({
            "error": f"Failed to process resolution agreement: {str(e)}"
        }), 500