const db = require('../../db');

const auth = async (body) => {
  try {
    const {login, password} = await body
    const [user] =
      await db('users').select(['id'])
        .whereNull('deletedAt')
        .andWhere('login', '=', login)
        .andWhere('password', '=', password)

    if(!!user){
      const {id} = user

      await db('users')
        .update('sessionToken', token)
        .where('id', '=', id)

      return {
        token
      }
    }else{
      return 'Unauthorized'
    }

  } catch (e) {
    return 'error' + e
  }
}

module.exports = auth;
