from flask import jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
import hashlib

def configure_auth(app):
    app.config['JWT_SECRET_KEY'] = 'super-secret'  # TODO: Replace with env var in prod
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 3600  # 1 hour

    # Auth routes
    @app.route('/api/login', methods=['POST'])
    def login():
        username = request.json.get('username')
        password = request.json.get('password')
        
        # TODO: Implement proper user store
        test_user = {
            'username': 'admin',
            'password': hashlib.sha256('admin'.encode()).hexdigest()
        }

        if not username or not password:
            return jsonify({"error": "Missing credentials"}), 400

        hashed_pw = hashlib.sha256(password.encode()).hexdigest()
        
        if username == test_user['username'] and hashed_pw == test_user['password']:
            access_token = create_access_token(identity=username)
            return jsonify(access_token=access_token), 200

        return jsonify({"error": "Invalid credentials"}), 401

    # Protected route example
    @app.route('/api/protected', methods=['GET'])
    @jwt_required()
    def protected():
        current_user = get_jwt_identity()
        return jsonify(logged_in_as=current_user), 200