module EmployerAutomation
  extend ActiveSupport::Concern

  included do

    scope :uninitialized, -> {
      where(initialized: false)
    }

    scope :initialized, -> {
      where(initialized: true)
    }

    scope :not_automation_ready, -> {
      where(group_number: [nil, ''])
    }

    scope :automation_ready, -> {
      where.not(group_number: [nil, ''])
    }

    scope :in_automation_initilization, -> {
      left_outer_joins(:id_card_setup)
        .where(initialized: false)
        .or(
          where(id_card_setup: {initialized: false})
        ).distinct
    }

    scope :missing_keychain_initialization, -> {
      uninitialized.automation_ready
    }

    scope :uninitialized_id_card_setup, -> {
      left_outer_joins(:id_card_setup)
        .where(id_card_setup: {initialized: false})
    }

    scope :missing_plans, -> {
      left_outer_joins(:plans)
        .where(id_card_plans: { pb_product_key: [nil, ""] })
        .distinct
    }

    scope :has_plans, -> {
      left_outer_joins(:plans)
        .where("id_card_plans.pb_product_key IS NOT NULL AND id_card_plans.pb_product_key != ''")
        .distinct
    }

    scope :missing_members, -> {
      left_outer_joins(:members)
        .where(members: { id: nil })
        .distinct 
    }

    scope :has_members, -> {
      left_outer_joins(:members)
        .where.not(members: { id: nil })
        .distinct 
    }

    scope :missing_plans_initialization, -> {
      initialized.uninitialized_id_card_setup.missing_plans
    }

    scope :missing_members_initialization, -> {
      initialized.uninitialized_id_card_setup.has_plans.missing_members
    }

    scope :ready_for_id_card_activation, -> {
      initialized.uninitialized_id_card_setup.has_members
    }

    scope :with_active_id_card_setup, -> {
      active.left_outer_joins(:id_card_setup)
        .where(id_card_setup: {active: true})
    }

    scope :deactivated, -> {
      inactive.initialized
    }
  end

  def sync_members_with_vhcs
    AutomationService::EmployerMembersUpdate.new(pl_plan_key).call
  end

  def sync_plans_with_vhcs
    AutomationService::EmployerPlansUpdate.new(pl_plan_key).call
  end

  def automation_identifier
    attributes.with_indifferent_access.slice(
      pl_plan_key.present? ? :pl_plan_key : :group_number
    )
  end

  def sync_with_vhcs
    employer_identifier = automation_identifier
    AutomationService::EmployerUpdate.new(employer_identifier).call
  end
end