import os

from flask import Flask
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from routes.auth import auth_bp
from routes.documents import documents_bp
from routes.users import users_bp
from routes.payments import payments_bp
from routes.subscriptions import subscriptions_bp

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "your-jwt-secret")
    app.config["JWT_TOKEN_LOCATION"] = ["headers", "query_string"]
    app.config["JWT_QUERY_STRING_NAME"] = "token"
    jwt = JWTManager(app)

    CORS(
        app,
        resources={r"/*": {"origins": [os.getenv("WEB_ORIGIN", "*")]}},
        allow_headers=["Authorization", "Content-Type"],
        expose_headers=["Content-Type"],
    )
    
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'instance/app_database.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    os.makedirs(app.instance_path, exist_ok=True)

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'
    
    app.register_blueprint(auth_bp, url_prefix="/auth")
    app.register_blueprint(documents_bp, url_prefix="/documents")
    app.register_blueprint(users_bp, url_prefix="/users")
    app.register_blueprint(payments_bp, url_prefix="/payments")
    app.register_blueprint(subscriptions_bp, url_prefix="/subscriptions")

    return app

if __name__=="__main__":
    app = create_app()
    app.run()