# frozen_string_literal: true

require './lib/knock_monkeypatch'

class Api::UserTokenController < Knock::AuthTokenController
  include Oath::ControllerHelpers
  include RememberMe::Controller

  skip_before_action :verify_authenticity_token
  before_action :sign_in_user

  rescue_from Exception, :with => :return_error

  # Catch exception and return JSON-formatted error
  def return_error(exception)
    Raven.capture_exception(exception)

    logger.error "==Handled======="
    logger.error exception.message
    logger.error exception.backtrace.join("\n")
    logger.error "==Handled======="
    case exception
    when ActiveRecord::RecordNotFound
      @status = 404
      @message = 'Record not found'
    when ActiveRecord::RecordInvalid
      @status = 422
      @message = 'Record invalid'
    when ArgumentError
      @status = 400
      @message = 'Argument Error'
    else
      @status = 500
      @message = 'Internal Error'
    end

    # for some reason render json_errors is not working
    # simulating JSON API support
    render json: {
      errors: [{
        status: @status.to_s,
        title: @message
      }]
    }
  end

  private

  def sign_in_user
    sign_in(entity)
  end
end
