class Admin::Legacy::Student::Students::Wisconsin::IdentitiesController <
    Admin::Legacy::Student::Controller
  def index
    response = identity_service.search
    unless response.key?(:error)
      render_success :ok, json: search_props(response)
    else
      render_error :unprocessable_entity, errors: response[:error]
    end
  end

  def show
    render_success :ok, json: identity_service.find(params[:id])
  end

  def create
    response = identity_service.create(params[:key])
    unless response.key?(:error)
      render_success :ok, message: 'Additional ID created.', json: response
    else
      render_error :unprocessable_entity, errors: response[:error]
    end
  end

  def missing_information
    render_success :ok, json: student.missing_required_identity_info
  end

  private
    def student
      @student ||= current_school.students.find_by(id: params[:student_id])
    end

    def identity_service
      EdFi::Wisconsin::IdentityService.new(current_school_year.id, student: student)
    end

    def gender_labels
      { 'male' => :Male, 'female' => :Female }
    end

    def search_props(response)
      return {} if response.nil?

      {}.tap do |props|
        props[:key] = response[:key]
        props[:records] = response[:body].map do |record|
          {
            id: record['uniqueId'],
            first_name: record['firstName'],
            last_name: record['lastSurname'],
            middle_name: record['middleName'],
            birth_date: record['birthDate'].to_date,
            gender: gender_labels[record['sexType']]
          }
        end
      end
    end
end
