import pg from 'pg';
import fs from 'fs';
import { logError } from './utils.js';
import { exec } from 'child_process';

const { Client } = pg;

const getClient = async () => {
    const client = new Client({
        user: process.env.POSTGRES_USER,
        password: process.env.POSTGRES_PASSWORD,
        host: process.env.POSTGRES_HOST,
        port: process.env.POSTGRES_PORT,
        database: process.env.POSTGRES_DB
    });
    await client.connect();

    await client.query(fs.readFileSync('./scheme.psql').toString());

    if ((await client.query("SELECT * FROM cities")).rowCount < 6079) {
        await client.query("DELETE FROM cities");

        //Not sure if pg has support for such kind of things, sooooooooo 
        exec(`PGPASSWORD=${process.env.POSTGRES_PASSWORD} psql -h ${process.env.POSTGRES_HOST} -p ${process.env.POSTGRES_PORT} -d ${process.env.POSTGRES_DB} -U ${process.env.POSTGRES_USER}  -f ./cities.sql`, (error) => {
            if (error) logError(error);
        })
    }

    return client;
};

export const db = await getClient();