class UpdateEmployerJob < ApplicationJob
  queue_as :default

  def perform(employer_identifier: {}, employer_plan_header: {}, full_sync: false)

    if employer_plan_header.present?
        pl_plan_key = employer_plan_header['PLPlanKey'].to_s
        employer_identifier[:pl_plan_key] = pl_plan_key
    elsif employer_identifier[:group_number]
        group_number = employer_identifier[:group_number]
        pl_plan_key = Vhcs::PlPlanGroupCode.find_by(group_code: group_number).pl_plan_key
    elsif employer_identifier[:pl_plan_key]
        pl_plan_key = employer_identifier[:pl_plan_key]
    end

    if pl_plan_key.present?

        if employer_plan_header.empty?
            sql_query = "SELECT PLPlanKey, PlanId, ShortDesc FROM PLPlanHeader WHERE PLPlanKey = #{pl_plan_key}"
            employer_plan_header = VhcsRecord.connection.select_all(sql_query).first
        end

        puts "== Updating #{employer_plan_header['ShortDesc'].strip.titleize} =="

        plan_code = Vhcs::HlPlanCode.find_by(plan_key: pl_plan_key)
        pb_company_plan = Vhcs::PbCompanyPlans.find_by(pl_plan_key: pl_plan_key)
        employer = Employer.find_or_create_by(employer_identifier)
        id_card_setup = employer.id_card_setup || employer.build_id_card_setup(pl_plan_key: employer.pl_plan_key)
        full_sync = employer.previously_new_record? || full_sync
        unless group_number.present?
            group_number = Vhcs::PlPlanGroupCode.find_by(pl_plan_key: pl_plan_key).group_code
        end

        employer_update_attrs = {}
        employer_update_attrs.merge!({
            plan_id: employer_plan_header['PlanId'].strip.to_i,
            company_pb_entity_key: pb_company_plan.company_pb_entity_key,
            group_number: group_number,
            pl_plan_key: pl_plan_key
        })
        
        if plan_code.present? && employer.effective_date.blank?
            employer_update_attrs.merge!({
                effective_date: plan_code.effect_date.strftime("%m/%d/%Y")
            })
        end

        if full_sync && employer.name.blank?
            employer_update_attrs.merge!({
                name: employer_plan_header['ShortDesc'].strip.titleize
            })
        end 

        employer.assign_attributes(employer_update_attrs)
        if !employer.save && full_sync 
            employer.save(validate: false)
        end

        if !employer.initialized && [employer.pl_plan_key, employer.group_number, employer.company_pb_entity_key, employer.plan_id].all?(&:present?)
            employer.update(active: true)
        end
        
        setup_update_attrs = {}
        if plan_code.present? && id_card_setup.rx_group_number.blank?
            setup_update_attrs.merge!({
                rx_group_number: plan_code.medical_number
            })
        end

        if full_sync || id_card_setup.print_name.blank?
            setup_update_attrs.merge!({
                print_name: determine_card_print_name(pb_company_plan.company_pb_entity_key, pl_plan_key)
            })
        end

        if id_card_setup.pl_plan_key.blank? && employer.pl_plan_key.present?
            setup_update_attrs.merge!({
                pl_plan_key: employer.pl_plan_key
            })
        end

        id_card_setup.assign_attributes(setup_update_attrs)
        if !id_card_setup.save && full_sync 
            id_card_setup.save(validate: false)
        end
            
            # plan_code = Vhcs::HlPlanCode.find_by(plan_key: employer.pl_plan_key)
            # employer.group_number = plan_code.group_number
            # id_card_setup.rx_group_number = plan_code.medical_number
            # employer.effective_date = plan_code.effect_date.strftime("%m/%d/%Y")
            
            # pb_company_plan = Vhcs::PbCompanyPlans.find_by(pl_plan_key: employer.pl_plan_key)
            # employer.company_pb_entity_key = pb_company_plan.company_pb_entity_key
            
            # card_print_name = Vhcs::PbEntity.where(company_pb_entity_key: employer.company_pb_entity_key, entity_type_id: 1007).last.last_name
            # id_card_setup.print_name = card_print_name

            # if employer.up_to_date?
            #     employer.active = true
            # end

            # employer.default_network_logo = determine_network_logos(employer.pl_plan_key)

        # plan_codes = Vhcs::HlEgglestonCardBenefit.where(plan_key: employer.pl_plan_key).pluck(:plan_id).uniq
        # employer_plans = employer.id_card_setup.plans
        # plan_titles = employer_plans.pluck(:title)
        # vhcs_plans = Vhcs::PbProduct.where(company_pb_entity_key: pb_company_plan.company_pb_entity_key, is_active: 255)
        # vhcs_plans.each do |vp|
        #     if employer_plans.present? && plan_titles.all?(&:present?) && employer_plans.find_by(pb_product_key: vp.pb_product_key).nil?
        #         plan_title_matcher = Amatch::JaroWinkler.new(vp.short_description)
        #         closest_title = plan_titles.max_by { |title| plan_title_matcher.match(title) }
        #         plan = employer_plans.find_or_create_by(title: closest_title)
        #         plan.update(
        #             title: vp.short_description,
        #             pb_product_key: vp.pb_product_key,
        #             pl_plan_key: employer.pl_plan_key
        #         )
        #         plan_titles.delete(closest_title)
        #     elsif employer_plans.blank?
        #         employer_plans.create!(
        #             pb_product_key: vp.pb_product_key,
        #             title: vp.short_description, 
        #             pl_plan_key: employer.pl_plan_key
        #         )
        #         # plan.update(
        #         #     title: vp.short_description, 
        #         #     pl_plan_key: employer.pl_plan_key
        #         # )
        #     end
        # end

    end
    employer.presence
  end

  private

  def determine_card_print_name(company_pb_entity_key, pl_plan_key)
    card_print_names = Vhcs::PbEntity.where(company_pb_entity_key: company_pb_entity_key, entity_type_id: 1007)
        .where.not("LastName LIKE ? OR LastName LIKE ? OR LastName LIKE ?", "%COBRA%", "Active", ".%").pluck(:last_name)
    if pl_plan_key == "2"
        "sm ART"
    elsif card_print_names.count > 2
        Employer.employer_trim_name(card_print_names.first)
    else
        card_print_names.last
    end
  end

end