const Pool = require('pg').Pool
const Contact = require('./../models/contact')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'project2',
  password: 'dbpassword',
  port: 5432,
})

// create the contacts table in the database if not already present
async function createContactsTable() {
	try {
		const query = `
			CREATE TABLE IF NOT EXISTS contacts (
				id SERIAL PRIMARY KEY,
				firstName VARCHAR(255) NOT NULL,
				lastName VARCHAR(255) NOT NULL,
				phoneNumber VARCHAR(255) NOT NULL,
				email VARCHAR(255) NOT NULL
			);
		`;

		await pool.query(query);
		console.log('Contacts table created');
		} catch (err) {
			console.error(err);
			console.error('Contacts table creation failed');
	}
}

// this will return all contacts in ascending order based off of the id
const getContacts = async (request, response) => {
    pool.query('SELECT * FROM contacts ORDER BY id ASC', (error, results) => {
      if (error) {
        console.error(error)  
        throw error
      }
      response.status(200).json(results.rows)
    })
  }

// This query will return all contacts that match the filter provided
// by the query parameters
// returns 200 with the matching contacts or a 404 with an appropriate 
// error message if none found with an empty array
const filterContacts = async (request, response) => {

}  


// This query will return the contact that matches the id in the request param
// returns 200 with the matching contact or a 404 with an appropriate 
// error message if none found with an empty array  
const getContactById = (request, response) => {
	
}

// creates a new contact in the database and will respond with a 200 status code
// if successful and should fail validations prior to reaching this query
// will respond with a 500 if the databse query fails
const createContact = (request, response) => {
  // create instance of Contact "class" and then apply validations on the data
  // instacne should be created from the request.body fields
  const { firstname, lastname, email, phonenumber } = request.body
  
  pool.query('INSERT INTO contacts (firstname, lastname, email, phonenumber) VALUES ($1, $2, $3, $4) RETURNING *', 
    [firstname, lastname, email, phonenumber], (error, results) => {
    if (error) {
      throw error
    }
    console.log(results.rows[0])
    console.log(results.fields)
    response.status(201).json({result: `User added with ID: ${results.rows[0].id}`})
  })
}

// updates an existing contact in the database and will respond with a 200 status code
// if successful and should fail validations prior to reaching this query
// will query for the contact based off of the request param
// will return a 404 if the resource is not found
// will also respond with the updated values for the contact resource
// will respond with a 500 if the databse query fails
  
const updateContact = (request, response) => {
	
}
  
  // deletes's contact from db - should first check that the contact exists and if not 
  // return a 404 with an appropriate error message
  // should respond with a 200 and the resource that was deleted if successfully
  // removed from the database
const deleteContact = (request, response) => {
	
}

module.exports = {
createContactsTable,
getContacts,
createContact
}