import { Connection, ConnectionConfiguration, Request } from "tedious";
import 'dotenv/config'

const MSSQL_HOST = process.env.MSSQL_HOST || 'localhost'
const MSSQL_LOGIN = process.env.MSSQL_LOGIN || 'sa'
const MSSQL_PASSWORD = process.env.MSSQL_PASSWORD || '' 
const MSSQL_DB = process.env.MSSQL_DB || 'nGeneral'
const MSSQL_PORT = Number(process.env.MSSQL_PORT) || 1433

const tediousConfig: ConnectionConfiguration = {
    server: MSSQL_HOST,
    options: {
        trustServerCertificate: true,
        port: MSSQL_PORT,
        database: MSSQL_DB
    },
    authentication: {
        type: 'default',
        options: {
            userName: MSSQL_LOGIN,
            password: MSSQL_PASSWORD
        }
    }
}

export function tediousQuery(query: string) {
    // Read all rows from table
    return new Promise((resolve, reject) => {
        const connection = new Connection(tediousConfig)

        connection.on('connect', (err) => {
            if (err) {
                reject(err)
                return
            }

            const result: any = [];

            const request = new Request(
                query,
                (err, rowCount) => {
                    if (err) {
                        console.log(`Executing ${query}, ${rowCount} rows.`);
                        console.error(err.message);
                    } else {
                        console.log(`Executing ${query}, ${rowCount} rows.`);
                    }
                }
            )

            request.on("row", (columns) => {
                const entry: any = {};
                columns.forEach((column: any) => {
                    entry[column.metadata.colName] = column.value;
                });
                result.push(entry);
            });

            request.on('error', error => reject(error));// some error happened, reject the promise
            request.on('requestCompleted', () => {
                connection.close();
                resolve(result)
            }); // resolve the promise with the result rows.

            connection.execSql(request)
        })

        connection.on('error', (err) => {
            reject(err)
        })

        connection.connect()
    });
}