'use strict'
const User = use('App/Models/User');
const EmailUtils = use('App/Utils/EmailUtils');
const RedisUtils = use('App/Utils/RedisUtils');
class AuthController {
  async registerIndex({view, auth, response}) {
    if (auth.user) {
      response.redirect('/');
      return;
    }
    return view.render('register')
  }

  async loginIndex({view, auth, response}) {
    if (auth.user) {
      response.redirect('/');
      return;
    }
    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: `/images/default-user-avatar.png`
    });
    if (user.id == 1) {
      user.is_admin = true;
    }
    await user.save();
    await auth.login(user);
    await EmailUtils.sendWelcomeEmail(user);
    response.redirect('/');
  }

  async login({request, response, auth, session}) {
    console.log('login');
    const {email, password} = request.all()
    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 resetPasswordRequest({request, response, session}) {
    const email = request.body.email;
    // check if user exists
    const queryResp = (await User.query().where({email}).fetch()).rows;
    if (!queryResp.length) {
      session.withErrors({userNotFound: 'No User with that email'}).flashAll();
      return response.redirect('back');
    }
    const user = queryResp[0];
    //
    const tokenPayload = {id: user.id, email: user.email};
    const token =
        await RedisUtils.ExpiredToken.generateResetPasswordToken(tokenPayload);
    const sent =
        await EmailUtils.sendResetPassword({name: user.name, email}, token);
    if (sent) {
      session.flash({notification: `Email sent to ${email} !`});
      response.redirect('/');
      return;
    }
    session.withErrors({message: 'Email provider error'}).flashAll();
    return response.redirect('back')
  }
  async resetPasswordRequestIndex({request, auth, response, view}) {
    if (auth.user) {
      response.redirect('/');
      return;
    }
    return view.render('reset-password-request');
  }
  async resetPasswordIndex({request, response, session, view}) {
    const token = request.params.token;
    const tokenPayload = await RedisUtils.ExpiredToken.getTokenPayload(token);
    if (!tokenPayload) {
      session.withErrors({InvalidToken: 'Token Expired or Invalid...'})
          .flashAll();
      response.redirect('/');
      return;
    } else {
      return view.render('reset-password', {token});
    }
  }

  async resetPassword({request, view, session, response}) {
    console.log('In function...');
    const {token, password, confirm} = request.all();
    if (password != confirm) {
      session.withErrors({confirm: 'Please make sure passwords match'})
          .flashAll();
      return response.redirect('back');
    }
    const tokenPayload = await RedisUtils.ExpiredToken.getTokenPayload(token);
    if (!tokenPayload) {
      session.withErrors({InvalidToken: 'Token Expired or Invalid...'})
          .flashAll();
      response.redirect('/');
      return;
    }
    const user = await User.find(tokenPayload.id);
    user.password = password;
    await user.save();
    /// TODO: send an email to notify user about the change;
    await RedisUtils.ExpiredToken.remove(token);
    session.flash({notification: `Password changed successfully`});
    return response.redirect('/');
  }

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

module.exports = AuthController
