class ApiRetailerInvitationsController < ApiController

  before_filter :api_signed_in_user
  before_filter :lookup_retailer, :only => [:index, :create]
  before_filter :auth_retailer, :only => [:index, :create]
  before_filter :lookup_retailer_invitation, :only => [:delete, :resend]
  before_filter :auth_retailer_invitation, :only => [:delete, :resend]

  respond_to :json

  def index
    data = RetailerInvitation.index(@retailer, params)

    @retailer_invitations = data[:query]

    @next = data[:next_page]
    render "api_retailer_invitations/index", :layout => nil
  end

  def create
    @retailer_invitation = RetailerInvitation.create(current_user, @retailer, params)

    if @retailer_invitation.errors.any?
      respond_with @retailer_invitation, status: :unprocessable_entity
      return
    end
  end

  def delete
    @retailer_invitation.destroy
    respond_with responder: ApiResponder, :status => 204
  end

  def resend
    @retailer_invitation.resend
  end

  private
  def lookup_retailer_invitation
    @retailer_invitation = RetailerInvitation.find_by_id(params[:invitation_id])
    raise ActiveRecord::RecordNotFound, "Can't find retailer invitation" if @retailer_invitation.nil?
  end

  def auth_retailer_invitation
    if current_user.id != @retailer_invitation.retailer.owner.id && current_user.id != @retailer_invitation.retailer.owner.id
      raise JamPermissionError, "You do not have access to this retailer"
    end
  end

  def lookup_retailer
    @retailer = Retailer.find_by_id(params[:id])
    raise ActiveRecord::RecordNotFound, "Can't find retailer" if @retailer.nil?
  end

  def auth_retailer
    if current_user.id != @retailer.owner.id && current_user.id != @retailer.owner.id
      raise JamPermissionError, "You do not have access to this retailer"
    end
  end
end

