from flask import Flask, request
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Enum
import enum
import os

file_path = os.path.abspath(os.getcwd()) + "/todo.db"
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + file_path
db = SQLAlchemy(app)


class Roles(enum.Enum):
    ADMIN = "admin"
    AUDITOR = "auditor"
    PROJECT_OWNER = "project_owner"
    BUYER = "buyer"


class User(db.Model):
    __tablename = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(200), unique=True, nullable=False)
    username = db.Column(db.String(200), unique=True, nullable=False)
    password_hash = db.Column(db.String(200), nullable=False)  # Store hashed password
    role = db.Column(db.Enum(Roles), nullable=False)
    blockchain_address = db.Column(db.String(42), unique=True)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f"User(username={self.username}, email={self.email}, role={self.role}, blockchain_address={self.blockchain_address})"


@app.route("/", methods=["GET"])
def home():
    return {"message": "Flask is running"}, 200


@app.route("/getdata", methods=["GET"])
def getdata():
    # Query all users from the database
    data = User.query.all()

    # Check if users exist in the database
    if not data:
        return {"message": "No users found in the database"}, 404

    # Convert user data to a list of dictionaries
    user_list = [
        {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'role': user.role.value,  # Access the value of the Enum
            'blockchain_address': user.blockchain_address
        }
        for user in data
    ]

    # Return the list of users
    return {'users': user_list}, 200


@app.route("/create_user", methods=["POST"])  # Renamed for clarity
def create_user():
    data = request.get_json()
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    role = data.get('role')
    blockchain_address = data.get('blockchain_address')

    if not username or not email or not password or not role:
        return {'error': 'All fields are required'}, 400

    try:
        # Convert the role from a string to the Enum
        user_role = Roles(role)
    except ValueError:
        return {"error": f"Invalid role: {role}. Must be one of {', '.join([r.value for r in Roles])}"}, 400

    # Create a new user instance
    new_user = User(username=username, email=email, role=user_role, blockchain_address=blockchain_address)
    new_user.set_password(password)  # Hash the password

    # Add the new user to the database
    db.session.add(new_user)
    db.session.commit()

    return {"message": "User created successfully"}, 200


if __name__ == '__main__':
    with app.app_context():
        db.create_all()  # Ensure database tables are created
    app.run(debug=True)

error:
❯ python user.py
Traceback (most recent call last):
  File "/home/devansh/dev/web3/antiC/backend/models/user.py", line 21, in <module>
    class User(db.Model):
  File "/home/devansh/dev/web3/antiC/backend/models/user.py", line 23, in User
    id = db.Column(db.Integer, primary_key=True)
         ^^^^^^^^^
  File "/home/devansh/.local/lib/python3.12/site-packages/flask_sqlalchemy/extension.py", line 982, in __getattr__
    if name in mod.__all__:
               ^^^^^^^^^^^
AttributeError: module 'sqlalchemy' has no attribute '__all__'. Did you mean: '__fi