class TokensController < ApplicationController
  skip_before_action :verify_authenticity_token
  respond_to :json

  def create
    email = params[:email]
    password = params[:password]
    if request.format != :json
      render status: 406, json: { message: 'The request must be json' }
      return
    end

    if email.nil? || password.nil?
      render status: 400,
             json: { message: 'The request must contain the user email and password.' }
      return
    end

    @user = User.where(['lower(email) = :value', { value: email.downcase }]).first

    if @user.nil?
      logger.info("User #{email} failed signin, user cannot be found.")
      render status: 401, json: { message: 'Invalid email or password.' }
      return
    end

    # http://rdoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable
    @user.ensure_authentication_token!

    if @user.valid_password? password
      render status: 200, json: { token: @user.authentication_token }
    else
      logger.info("User #{email} failed signin, password \"#{password}\" is invalid")
      render status: 401, json: { message: 'Invalid email or password.' }
    end
  end

  def destroy
    @user = User.find_by(authentication_token: params[:id])
    if @user.nil?
      logger.info('Token not found.')
      render status: 404, json: { message: 'Invalid token.' }
    else
      @user.reset_authentication_token!
      render status: 200, json: { token: params[:id] }
    end
  end
end
