class UpdateEmployerPlansJob < ApplicationJob
  queue_as :default

  def perform(pl_plan_key)
    
    employer = Employer.includes(:id_card_setup).find_by(pl_plan_key: pl_plan_key)
    setup = employer.id_card_setup
    puts "== Updating #{employer.name} Plans =="

    pb_company_plan = Vhcs::PbCompanyPlans.find_by(pl_plan_key: pl_plan_key)
    
    vhcs_card_plans = Vhcs::PbProduct.where(company_pb_entity_key: pb_company_plan.company_pb_entity_key, is_active: 255).where.not("ShortDescription LIKE ?", "%Vision%")
    unless setup.has_dental
        vhcs_card_plans = vhcs_card_plans.where.not("ShortDescription LIKE ?", "%Dental%")
    end
    vhcs_card_plan_product_keys = vhcs_card_plans.pluck(:pb_product_key)
    vhcs_card_plan_titles = vhcs_card_plans.pluck(:short_description).map(&:strip)

    employer_plans = employer.id_card_setup.plans
    employer_plan_product_keys = employer_plans.pluck(:pb_product_key)
    employer_plan_titles = employer_plans.pluck(:title)
    plans_without_product_key = employer_plans.where(pb_product_key: ["", nil])

    new_card_plan_pb_product_keys = vhcs_card_plan_product_keys - employer_plan_product_keys

    vhcs_card_plans_to_import = Vhcs::PbProduct.where(pb_product_key: new_card_plan_pb_product_keys)
    vhcs_card_plans_to_import.each do |vhcs_plan_import|
        # if employer_plans.present? && plan_titles.all?(&:present?) && employer_plans.find_by(pb_product_key: vhcs_plan.pb_product_key).nil?
        # if employer_plans.find_by(pb_product_key: vhcs_plan.pb_product_key).nil?

        if plans_without_product_key
            plan_title_matcher = Amatch::JaroWinkler.new(vhcs_plan_import.short_description.strip)
            title_match = employer_plan_titles.max_by { |title| plan_title_matcher.match(title) }
            plan = employer_plans.find_or_create_by(title: title_match)
            plan.update(
                pb_product_key: vhcs_plan_import.pb_product_key,
                title: vhcs_plan_import.short_description.strip,
                pl_plan_key: employer.pl_plan_key
            )
            employer_plan_titles.delete(title_match)
        else
            employer_plans.create!(
                pb_product_key: vhcs_plan_import.pb_product_key,
                title: vhcs_plan_import.short_description.strip, 
                pl_plan_key: employer.pl_plan_key
            )
        end
    end

    employer
  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