import Datastore from 'pg';
import {config} from '../config.js';

class DbService {
    client = new Datastore.Client({
        user: "clicker",
        host: config.env.hostnameDb,
        database: "cookiedb",
        password: "3kwzcbKqxT_ephM_wr3n",
        port: 5432
    });

    constructor() {
        // Queries to fill database
        const initDbQuery = `
        CREATE TABLE IF NOT EXISTS room (
            id SERIAL UNIQUE PRIMARY KEY,
            name VARCHAR(50) NOT NULL,
            count INTEGER NOT NULL
        );

        CREATE TABLE IF NOT EXISTS users (
            id SERIAL UNIQUE PRIMARY KEY,
            username VARCHAR(50) NOT NULL,
            firstname VARCHAR(50) NOT NULL,
            lastname VARCHAR(50) NOT NULL,
            email VARCHAR(100) NOT NULL,
            password VARCHAR(250) NOT NULL
        );
        
        CREATE TABLE IF NOT EXISTS roomassignment (
          userid INTEGER NOT null references users(id),
          roomid INTEGER NOT null references room(id),
          PRIMARY KEY (userid, roomid)
        );
        
        
        
        `;

        this.client
            .connect()
            .catch(err => console.error('connection error', err.stack));

        this.client.query(initDbQuery)
            .then(res => {
                //
            })
            .catch(err => console.log(err.stack));

    }
}

export const dbService = new DbService();