require "byebug"
require "mysql2"
require "sequel"
require 'odbc'

# For math
require "bigdecimal"
require "bigdecimal/util"

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end

  config.disable_monkey_patching!
  config.warnings = true
  config.order = :random
  Kernel.srand config.seed
end

def mysql
  @mysql ||= Mysql2::Client.new(
    host: ENV["MYSQL_HOST"],
    username: ENV["MYSQL_USER"],
    password: ENV["MYSQL_PASS"]
  )
end

def snowflake
  @snowflake ||= Sequel.odbc(ENV["SNOWFLAKE_DSN"], user: ENV["SNOWFLAKE_USER"], password: ENV["SNOWFLAKE_PASSWORD"])
end

def get_current_accounting_period_snowflake
  snowflake_query = "SELECT max(accountingperiodid) AS latest_period FROM fact_sales"
  snowflake.fetch(snowflake_query)
end

def get_current_accounting_period_art_relations
  art_relations_query = "SELECT max(period_id) AS latest_period FROM art_relations.period where status = 'processing';"
  mysql.query(art_relations_query)
end

# Obtaining a current accounting period in case it wasn't set
def get_current_accounting_period
  art_relations_results = get_current_accounting_period_art_relations
  snowflake_results = get_current_accounting_period_snowflake
  snowflake_period = snowflake_results.first[:latest_period].to_s
  art_relations_period = art_relations_results.first["latest_period"].to_s
  fail "Current accounting period from art_relations (#{art_relations_period}) didn't match snowflake (#{snowflake_period})" if snowflake_period != art_relations_period
  snowflake_period
end

RSpec.configuration.before(:suite) do
  current_accounting_period = get_current_accounting_period
  if ENV["PERIOD"].nil? || (ENV["PERIOD"] == "")
    p "============================================================"
    p "PERIOD value was not set manually, setting to current accounting period: #{current_accounting_period}"
    ENV["PERIOD"] = current_accounting_period
    p "============================================================"
  end
end
