class
ApiSchoolInvitationsController < ApiController

  before_filter :api_signed_in_user
  before_filter :lookup_school, :only => [:index, :create]
  before_filter :auth_school, :only => [:index, :create]
  before_filter :lookup_school_invitation, :only => [:delete, :resend]
  before_filter :auth_school_invitation, :only => [:delete, :resend]

  respond_to :json

  def index
    data = SchoolInvitation.index(@school, params)

    @school_invitations = data[:query]

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

  def create
    @school_invitation = SchoolInvitation.create(current_user, @school, params)

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

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

  def resend
    @school_invitation.resend
  end

  private
  def lookup_school_invitation
    @school_invitation = SchoolInvitation.find_by_id(params[:invitation_id])
    raise ActiveRecord::RecordNotFound, "Can't find school invitation" if @school_invitation.nil?
  end

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

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

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

