module AutomationService
    class EmployerMembersUpdate

        def initialize(pl_plan_key)
            @pl_plan_key = pl_plan_key
        end

        def call
            employer = Employer.includes(:id_card_setup).find_by(pl_plan_key: @pl_plan_key)
            card_setup = employer.id_card_setup
            puts "-- #{employer.name}"

            # employer_members =[]
            vw_mb_members = Vhcs::VwmbMember.where(enrollee_type_value_id: 1, pl_plan_key: @pl_plan_key).select(:mb_member_key, :pb_entity_key, :pl_plan_key, :family_id, :full_name_last_name_first, :social_security_number)
            # vw_mb_members.each do |vw_mb_member|
            #     member = UpdateMemberJob.perform_now(@pb_entity_key, employer.id, card_setup.has_divisions, card_setup.has_dental, true, vw_mb_member)
            # end
            # employer.members = employer_members
            # employer.save

            member_update_futures = vw_mb_members.map do |vw_mb_member|
                Concurrent::Future.execute do
                    ActiveRecord::Base.connection_pool.with_connection do
                        UpdateMemberJob.perform_now(vw_mb_member.pb_entity_key, employer.id, card_setup.has_divisions, card_setup.has_dental, vw_mb_member)
                    end
                end
            end

            member_updates = member_update_futures.map(&:value).compact
            employer.members = member_updates
            if member_updates.empty? && employer.id_card_setup.active
                employer.active = false
            end
            employer.save

        end        
    end
end