module BenefitsWordDocService
    class MapEmployerInformation

        def initialize(employer, word_doc_section)
            @employer = employer
            @card_setup = @employer.id_card_setup
            @word_doc_section = word_doc_section
        end

        def call
            search_fields = mapping_hash.keys.to_set

            @word_doc_section.each do |line|
                matching_field = search_fields.detect { |field| line.include?(field) }
                if matching_field
                    field_mapping = mapping_hash[matching_field]
                    field_regex = field_mapping[:doc_to_employer_regex]
                    field_value = line.match(field_regex)[1].strip
                    employer_field = field_mapping[:employer_field]

                    if field_mapping[:validation].present?
                        validation_type = field_mapping[:validation]
                        if send("is_#{validation_type}?".to_sym, field_value)
                            @employer[employer_field] = field_value
                        end
                    else
                        @employer[employer_field] = field_value
                    end
                end
            end
            @card_setup.print_name = @employer.name
            @employer.name = @employer.name.titleize
            @card_setup.rx_group_number = @employer.group_number
            @employer
        end

        private

        def mapping_hash
            {
                'Employer Name' => {
                    employer_field: :name,
                    doc_field: 'Employer Name',
                    doc_field_desc: 'Follows pattern - Employer Name:New Employer',
                    doc_to_employer_regex: /.*:(.*)/,
                    regex_desc: 'Grabs everything after colon'
                },
                'Group Number' => {
                    employer_field: :group_number,
                    doc_field: 'Group Number',
                    doc_field_desc: 'Follows pattern - Group Number:099999',
                    doc_to_employer_regex: /.*:(.*)/,
                    regex_desc: 'Grabs everything after colon',
                    validation: 'number'
                },
                'Group Effective Date' => {
                    employer_field: :effective_date,
                    doc_field: 'Group Effective Date',
                    doc_field_desc: 'Follows pattern - Group Effective Date:12/1/2025',
                    doc_to_employer_regex: /.*:(.*)/,
                    regex_desc: 'Grabs everything after colon',
                    validation: 'date'
                }
            }
        end

        def is_number?(string)
            true if Float(string) rescue false
        end

        def is_date?(string)
            true if Date.parse rescue false
        end

    end
end