'use strict'
const User = use('App/Models/User')
class AuthController {
  async registerIndex({view}) {
    return view.render('register')
  }

  async loginIndex({view}) {
    return view.render('login')
  }

  async register({request, response, view, session, auth}) {
    const user = await User.create({
      email: request.input('email'),
      name: request.input('name'),
      password: request.input('password'),
      avatar:
          `https://api.adorable.io/avatars/285/${request.input('email')}.png`
    });
    if (user.id == 1) {
      user.is_admin = true;
    }
    await user.save();
    await auth.login(user)
    response.redirect('/');
  }

  async login({request, response, auth, session}) {
    console.log('login');
    const {email, password} = request.all()
    console.log({email, password})
    try {
      const token = await auth.attempt(email, password);
      const user = auth.user;
      // user.last_logged_in = new Date();
      // await user.save();
      console.log('logged in');
    } catch (e) {
      console.error(e);
      session.withErrors({loginError: 'Invalid Credentials'}).flashAll()
      return response.redirect('back')
    }


    response.redirect('/');
  }

  async logout({auth, response}) {
    await auth.logout();
    response.redirect('/');
  }
}

module.exports = AuthController
