from flask import Flask, request,jsonify
import os
from dotenv import load_dotenv
from functools import wraps
from services.get_survey import GetSurveyService
from services.get_survey_questions import GetSurveyQuestionsService

# Load the environment variables from .env file
load_dotenv()

STATIC_API_KEY = os.getenv('STATIC_API_KEY')

app = Flask(__name__)

# Custom middleware function to check API key
def require_api_key(view_function):
    @wraps(view_function)  # Preserve the original function's name
    def decorated_function(*args, **kwargs):
        api_key = request.headers.get('X-API-Key')

        if api_key and api_key == STATIC_API_KEY:
            return view_function(*args, **kwargs)
        else:
            return jsonify({'error': 'Unauthorized access'}), 401

    return decorated_function

#Get survey from odoo
@app.route("/api/survey", methods=["GET"])
@require_api_key
def get_survey():
    survey_id = request.args.get("survey_id")
    survey_data = GetSurveyService.get_survey_service(survey_id)
    
    # Ensure the survey data is valid, otherwise return an error response
    if survey_data is None:
        return jsonify({'status': 'error', 'message': 'Survey not found'}), 404
    
    return jsonify({'status': 'success', 'data': survey_data}), 200

# Route to get survey questions by survey_id
@app.route("/api/survey/<int:survey_id>/questions", methods=["GET"])
@require_api_key
def get_survey_questions(survey_id):
    survey_data = GetSurveyQuestionsService.get_survey_questions_service(survey_id)

    # Ensure the survey data is valid, otherwise return an error response
    if survey_data is None:
        return jsonify({'status': 'error', 'message': 'Survey not found'}), 404

    return jsonify({'status': 'success', 'data': survey_data}), 200

if __name__ == "__main__":
    app.run(debug=True)
