from flask import Blueprint, request, jsonify
from models import db, User

from flask import Blueprint, request, jsonify
from models import db, User, LinkCode
from datetime import datetime

api_bp = Blueprint('api', __name__)

@api_bp.route('/link', methods=['POST'])
def link_account():
    data = request.json
    code = data.get('code')
    uuid = data.get('uuid')
    username = data.get('username')
    
    if not code or not uuid or not username:
        return jsonify({'success': False, 'message': 'Missing data'}), 400
        
    # Check code in database
    link_entry = LinkCode.query.filter_by(code=code).first()
    
    if not link_entry:
        return jsonify({'success': False, 'message': 'Invalid code'}), 400
        
    if link_entry.expires_at < datetime.utcnow():
        db.session.delete(link_entry)
        db.session.commit()
        return jsonify({'success': False, 'message': 'Code expired'}), 400
        
    user = User.query.get(link_entry.user_id)
    if not user:
        return jsonify({'success': False, 'message': 'User not found'}), 404
        
    if user.minecraft_uuid:
        return jsonify({'success': False, 'message': 'User already linked'}), 400
        
    user.minecraft_uuid = uuid
    user.minecraft_username = username
    
    # Remove the used code
    db.session.delete(link_entry)
    db.session.commit()
    
    return jsonify({'success': True, 'message': f'Successfully linked to {user.username}'})
