from ..services.mysql_service import get_db_connection
import bcrypt

class AuthModel:
    @staticmethod
    def validate_credentials(username, password):
        """Validate user credentials against the database."""
        print(f"DEBUG: Validating credentials for user: {username}")
        conn = get_db_connection()
        if not conn:
            print("DEBUG: Validation failed - could not connect to database.")
            return False

        try:
            cursor = conn.cursor(dictionary=True)
            query = "SELECT password FROM users WHERE username = %s"
            cursor.execute(query, (username,))
            user = cursor.fetchone()
            
            if user:
                print("DEBUG: User found in database.")
                if bcrypt.checkpw(password.encode('utf-8'), user['password'].encode('utf-8')):
                    print("DEBUG: Password check successful.")
                    return True
                else:
                    print("DEBUG: Password check failed.")
                    return False
            else:
                print("DEBUG: User not found in database.")
                return False
        except Exception as e:
            print(f"DEBUG: FATAL: Error during credential validation: {e}")
            return False
        finally:
            if conn.is_connected():
                cursor.close()
                conn.close()

    @staticmethod
    def register_user(username, password):
        """Register a new user in the database."""
        hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
        conn = get_db_connection()
        if not conn:
            raise Exception("Could not connect to the database")

        try:
            cursor = conn.cursor()
            query = "INSERT INTO users (username, password) VALUES (%s, %s)"
            cursor.execute(query, (username, hashed_password.decode('utf-8')))
            conn.commit()
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            if conn.is_connected():
                cursor.close()
                conn.close()

    @staticmethod
    def get_user_role(pid):
        """Fetches the role for a given user PID."""
        conn = get_db_connection()
        if not conn:
            return 'Staff' # Default role if DB connection fails

        role = 'Staff' # Default role
        try:
            cursor = conn.cursor(dictionary=True)
            query = """
                SELECT r.name as role_name 
                FROM staff_roles sr
                JOIN roles r ON sr.role_id = r.id
                WHERE sr.pid = %s
            """
            cursor.execute(query, (pid,))
            role_record = cursor.fetchone()
            if role_record:
                role = role_record['role_name']
        except Exception as e:
            print(f"Error fetching role for pid {pid}: {e}")
        finally:
            if conn.is_connected():
                cursor.close()
                conn.close()
        return role
