# frozen_string_literal: true

module CsvExportable
  extend ActiveSupport::Concern

  COMMON_HEADERS = %i[notes tags signed_at].freeze
  COMMON_VALUES = %w[clean_notes clean_tags signed_on].freeze

  included do
    class << self
      def custom_csv_exportable_headers
        []
      end

      def csv_headers
        headers = custom_csv_exportable_headers + COMMON_HEADERS

        headers.map do |header|
          I18n.t("#{model_name.plural}.index.table_headers.#{header}")
        end
      end
    end

    def to_csv_row
      (self.class.custom_csv_exportable_headers + COMMON_VALUES).map do |function|
        send(function)
      end
    end

    private

    def contact_info
      contact_info = ''
      contact_info += "#{person_address}; " if person_address.present?
      contact_info += "P: #{person_phone}; " if person_phone.present?
      contact_info += "E: #{person_email}" if person_email.present?
      contact_info.delete_suffix '; '
    end

    def clean_notes
      notes = ''
      self.notes.order_by_recent.each do |note|
        notes += "#{note.content}(#{note.email}), "
      end
      notes.delete_suffix ', '
    end

    def clean_tags
      tags = ''
      self.tags.each do |tag|
        tags += "#{tag.name}, "
      end
      tags.delete_suffix ', '
    end
  end
end
