"""
https://chartio.com/resources/tutorials/how-to-execute-raw-sql-in-sqlalchemy/
"""
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, VARCHAR, Date, text

COINBASE_API_kEY_NAME = "coinbase_api_key"
COINBASE_API_SECRET_KEY_NAME = "coinbase_api_secret"


def fetch_api_secret_from_db(session, user_id: str):
    sql = text(f'select credentials_key, credentials_value from (select * from babylon_users.credentials where user_id="{user_id}") creds where credentials_key="{COINBASE_API_SECRET_KEY_NAME}"')  # noqa
    result = session.execute(sql).fetchall()

    def _extract_api_secret(db_result):
        """
        Helper method for extracting coinbase api key from the select result.
        """
        return db_result[0][1]

    return _extract_api_secret(result)


def fetch_api_key_from_db(session, user_id: str):
    sql = text(f'select credentials_key, credentials_value from (select * from babylon_users.credentials where user_id="{user_id}") creds where credentials_key="{COINBASE_API_kEY_NAME}"')  # noqa
    result = session.execute(sql).fetchall()

    def _extract_api_key(db_result):
        """
        Helper method for extracting api key from th eselect result.
        """
        return db_result[0][1]

    return _extract_api_key(result)
