import sqlite3 from 'sqlite3'
import { open } from 'sqlite'

let db = null
let error = null

const dbInit = open({
  filename: './sqlite.db',
  driver: sqlite3.Database
})
  .then((database) => {
    db = database
    console.log('Connected to the database.')
  })
  .catch((err) => {
    console.error('Error opening database: ' + err.message)
    error = err
    console.log(err)
  })

const getDb = async () => {
  await dbInit
  if (!db) throw new Error('Database not initialized.')
  return db
}

const getServers = async (db) => {
  return await db.all('SELECT * FROM servers')
}

const getServerByCol = async (db, col, val) => {
  const data = await db.all('SELECT * FROM servers WHERE ? = ?', [col, val])
  if(!data[0]) throw 'NOTFOUND'
  return data[0]
}

export { getDb, getServers, getServerByCol }

// const getProducts = async () => {
//   const db = await getDb()
//   return await db.all('SELECT * FROM Product')
// }

// const getProductById = async (id) => {
//   const db = await getDb()
//   const data = await db.all('SELECT * FROM Product WHERE id = ?', [id])
//   if (!data[0]) throw 'NOTFOUND'
//   return data[0]
// }

// const updateProduct = async (
//   id,
//   code,
//   price,
//   name
// ) => {
//   const db = await getDb()
//   await db.run('UPDATE Product SET code = ?, price = ?, name = ? WHERE id = ?', [
//     code,
//     price,
//     name,
//     id
//   ])
// }

// const addProduct = async (code, price, name) => {
//   const db = await getDb()
//   await db.run('INSERT INTO Product (code, price, name) VALUES (?, ?, ?)', [code, price, name])
// }

// const removeProduct = async (id) => {
//   const db = await getDb()
//   await db.run('DELETE FROM Product WHERE id = ?', [id])
// }

// const getProductByCode = async (code) => {
//   const db = await getDb()
//   const data = await db.all('SELECT * FROM Product WHERE code = ?', [code])
//   if (!data[0]) throw 'NO_DATA'
//   return data[0]
// }