from flask import Flask, jsonify, make_response, session
from src import db, bcrypt
from src.utils.decorators import handle_exceptions
from flask_cors import CORS
from env import DATABASE_URI, FRONTEND_URI, SECRET_KEY
from src.routes import teachers_bp, students_bp, schools_bp, admin_bp, principals_bp
from src.utils.helper import current_user


def create_app():
    app = Flask(__name__)
    CORS(app, origins=FRONTEND_URI, supports_credentials=True)

    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config['SECRET_KEY'] = SECRET_KEY

    db.init_app(app)
    bcrypt.init_app(app)
    
    @app.get("/")
    @handle_exceptions
    def root():
        return jsonify({
            "success": True,
            "message": "Welcome to the SolveSmart API"
        })
        
    @app.route("/logout")
    def logout():
        resp = make_response(jsonify({
            "success": True,
            "message": "Logout successfully"
        }))
        resp.delete_cookie("auth_token")
        session.clear()
        return resp
        
    @app.route("/get_curr_user")
    def get_curr_user():
        return current_user()
    
    app.register_blueprint(teachers_bp)
    app.register_blueprint(students_bp)
    app.register_blueprint(schools_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(principals_bp)

    with app.app_context():
        db.create_all()

    return app


app = create_app()

if __name__ == "__main__":
    app.run(debug=True)