class LegacyDbModelGenerator < Rails::Generators::Base
  source_root File.expand_path('templates', __dir__)

  argument :db_name, type: :string, required: true
  argument :table_name, type: :string, required: true

  def determine_db_record
    if db_name == 'VHCS_HIPAA'
      @db_record = 'VhcsRecord'.constantize
      @module = 'Vhcs'.constantize
      @file_folder = 'vhcs'
    elsif db_name == 'BrittonWeb'
      @db_record = 'BrittonWebRecord'.constantize
      @module = 'BrittonWeb'.constantize
      @file_folder = 'britton_web'
    elsif db_name == 'HEBWeb'
      @db_record = 'WebRecord'.constantize
      @module = 'HebWeb'.constantize
      @file_folder = 'heb_web'
    else
      raise LegacyDBModelError, "Invalid database, please use VHCS_HIPAA or HEBWeb"
    end
  end

  def get_fields_if_table_exists
    tn = table_name.strip
    if @db_record.connection.table_exists?(tn) || @db_record.connection.view_exists?(table_name)
      @fields = @db_record.connection.columns(tn).map { |col| col.name }
    else
      raise LegacyDBModelError, "Invalid table/view for #{db_name}, please double check spelling and capitalization"
    end
  end


  # Add argurment for database, depending on db - change AR::Base below to correct db record
  # Find out way to error out if table not found


  # use this code to get table field names here, convert to underscore,
  # send as aray or array pairs, and pass to template.
  # columns = ActiveRecord::Base.connection.columns(table_name)
  # field_names = columns.map(&:name)

  def create_model_file
    template "legacy_model.rb.erb.tt", "app/models/#{@file_folder}/#{file_name}.rb"
  end

  # kick off another schema dump and rebuild alt db schema
  # Will need to persist what tables to run (maybe in db, maybe in alt db schema)

  private

  def file_name
    "#{table_name.underscore}"
  end

  def class_name
    "#{table_name.camelize}"
  end

  def uddt_type_mapping
    {
      "uddtBaseKey" => "integer, limit: 8",
      "uddtIdPlan" => "string",
      "uddtBaseEnum" => "uddt_base_enum",
      "uddtBaseShortDesc" => "string",
      "uddtBaseLongDesc" => "string",
      "uddtBaseContact" => "string",
      "uddtAddrCity" => "string",
      "uddtAddrState" => "string",
      "uddtAddrStreet" => "string",
      "uddtAddrZip" => "string",
      "uddtContPhone" => "string",
      "uddtIdTax" => "string",
      "uddtNotesNote" => "string",
      "uddtFooter" => "string",
      "uddtBaseDate" => "datetime",
      "uddtBaseUserId" => "string"
    }
  end

  class LegacyDBModelError < StandardError; end
end
