class EmployerSetupProcess < ApplicationRecord
  has_many :plans, dependent: :destroy
  accepts_nested_attributes_for :plans, allow_destroy: true, reject_if: :all_blank

  has_many :alternate_network_logos, dependent: :destroy
  accepts_nested_attributes_for :alternate_network_logos, allow_destroy: true, reject_if: :all_blank

  has_many :card_logo_files

  # before_save :process_employer_logo
  before_save :create_slug, if: :new_record?

  def process_employer_logo
    if self.employer_logo.present? && !self.employer_logo.is_a?(String)
      self.card_logo_files.new(
        filename: self.employer_logo.filename, 
        logo_type: 'employer',
        image: self.employer_logo.data,
        pl_plan_key: self.pl_plan_key || ""
      )
    end
  end

  def create_slug
    self.slug = employer_trimmed_name.parameterize
  end

  def employer_name_to_logo_filename(extension)
    self.employer_trimmed_name.titleize.gsub(/\s+/, '').concat('Logo').concat(extension.downcase)
  end

  def employer_trimmed_name
    regex_source  = Regexp.union(["health", "plan", "the", "inc", "llc"]).source
    case_insensitive_regex = Regexp.new(regex_source, "i")
    self.employer_name.gsub(case_insensitive_regex, "").squish
  end

  def self.permitted_params(params)
    params.require(:employer_setup_process).permit(
      :employer_name,
      :group_number,
      :pl_plan_key,
      :effective_date,
      :employer_logo,
      :network_provider,
      plans_attributes: [
        :id,
        :title,
        :plan_id,
        :_destroy,
        plan_benefits_attributes: [
          :id,
          :benefit_desc,
          :benefit,
          :sequence,
          :_destroy,
        ]
      ],
      alternate_network_logos_attributes: [
        :id,
        :network_logo,
        :exception_type,
        :exception_value,
        :_destroy
      ]
    )
  end

  def save_to_prod

    VhcsRecord.transaction do
      Vhcs::HlPlanCode.create!(
        group_number: self.group_number,
        medical_number: self.group_number,
        dental_number: '',
        plan_key: self.pl_plan_key,
        effect_date: self.effective_date
      )

      # Replace fairos_info with template like for benefits
      fairos_info = Vhcs::HlrxCrosRef.where(pl_plan_key: 52).first
      Vhcs::HlrxCrosRef.cdarreate!(
        group_no: self.group_number,
        rx_group_id: self.group_number,
        help_desk: fairos_info.help_desk,
        customer_service: fairos_info.customer_service,
        web_url: fairos_info.web_url,
        pl_plan_key: self.pl_plan_key
      )

      self.plans.each_with_index do |plan, i|
        plan.plan_benefits.each do |bene|
          Vhcs::HlEgglestonCardBenefit.create!(
            plan_id: plan.plan_id,
            benefit_desc: bene.benefit_desc,
            benefit: bene.benefit,
            sequence: bene.sequence,
            plan_key: self.pl_plan_key
          )
        end
      end
    end

  end

end
