$months_to_keep = 6

ENV['RAILS_ENV'] = 'production'

$:.unshift '/srv/www/apps/revenue_accounting'
require 'config/environment'

def drop_before_months(months)
  conn = ActiveRecord::Base.connection
  cutoff = Date.default - months.months
  pa = Partitioned::Action
  %w(
    owner_amounts
    journal_results
    owner_billing_results
    allocated_results
    asset_owner_amounts
    jib_audit_data
    gl_transactions
  ).each do |table|
    klass = pa.class_for_table(table)
    puts "Dropping #{table} before #{cutoff}"
    if table == "gl_transactions"
      keys = "accounting_periods"
      where = "fiscal_year < #{cutoff.year} OR (fiscal_year = #{cutoff.year} AND fiscal_period < #{cutoff.month})"
    else
      keys = "moments"
      where = "accounting_date < '#{cutoff.to_s(:db)}'"
    end
    klass.all_zones.each do |zone|
      table = klass.table_name_for_zone(zone)
      pf = klass.partition_function(zone)
      parts = conn.select_values <<-SQL
        WITH ids AS (
          SELECT CAST(partition_boundary_value AS int) AS id
          FROM partition_info
          WHERE table_name = '#{table}'
          AND partition_row_count > 0
          INTERSECT
          SELECT id
          FROM #{keys}
          WHERE #{where}
        )
        SELECT $partition.#{pf}(id) FROM ids
      SQL
      parts.each do |part|
        pa.switch_and_drop(klass, table, part)
      end
    end
  end
  %w(
    financial_integrations
  ).each do |table|
    puts "Dropping #{table} before #{cutoff}"
    conn.execute <<-SQL
      DELETE t
      FROM #{table} t
      JOIN moments m
      ON t.moment_id = m.id
      WHERE m.accounting_date < '#{cutoff.to_s(:db)}'
    SQL
  end
end

drop_before_months($months_to_keep)
