import os
from dotenv import load_dotenv
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager



# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()

from padel import paginas, reservas, basededatos, auth

load_dotenv()

def create_app():
    app = Flask(__name__)
    app.config.from_prefixed_env()


    app.config['SECRET_KEY'] = 'secret-key-goes-here'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)
    
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))
    
    from . import models

    with app.app_context():
        db.create_all()

    basededatos.init_app(app)

    app.register_blueprint(paginas.bp)
    app.register_blueprint(reservas.bp)
    app.register_blueprint(auth.bp)

    print(f"Current Environment: {os.getenv('ENVIRONMENT')}")
    print(f"Using Database: {app.config.get('DATABASE')}")

    return app

