module Finance

  def self.freeze_closed_invoices_raw
    vat_rate_cmd = "UPDATE invoices i LEFT JOIN accounts buyer ON i.buyer_account_id = buyer.id SET i.vat_rate = buyer.vat_rate;"

    address_cmd = """
UPDATE invoices i

LEFT JOIN accounts provider ON i.provider_account_id = provider.id
LEFT JOIN accounts buyer ON i.buyer_account_id = buyer.id

LEFT JOIN countries provider_country ON provider.country_id = provider_country.id
LEFT JOIN countries buyer_country ON buyer.country_id = buyer_country.id

LEFT JOIN billing_strategies bs ON bs.account_id = provider.id

SET
	i.fiscal_code = buyer.fiscal_code,
	i.vat_code = buyer.vat_code,
	i.currency = bs.currency,

	i.from_address_name = provider.org_name,
	i.from_address_line1 = provider.org_legaladdress,
	i.from_address_line2 = provider.org_legaladdress_cont,
	i.from_address_city = provider.city,
	i.from_address_region = provider.state_region,
	i.from_address_state = provider.state_region,
	i.from_address_country = provider_country.name,
	i.from_address_zip = provider.zip,
	i.from_address_phone = provider.telephone_number,

	i.to_address_name = buyer.org_name,
	i.to_address_line1 = buyer.org_legaladdress,
	i.to_address_line2 = buyer.org_legaladdress_cont,
	i.to_address_city = buyer.city,
	i.to_address_region = buyer.state_region,
	i.to_address_state = provider.state_region,
	i.to_address_country = buyer_country.name,
	i.to_address_zip = buyer.zip,
	i.to_address_phone = buyer.telephone_number

WHERE i.state IN ('pending', 'unpaid', 'cancelled', 'failed', 'paid');
"""

    puts 'Caching vat_rates'
    Invoice.connection.execute(vat_rate_cmd)

    puts 'Freezing addresses'
    Invoice.connection.execute(address_cmd)
  end



  # TODO: remove this file when Rails3 are succesfully deployed.
  #
  def self.freeze_closed_invoices
    Invoice.reset_column_information
    all = Invoice.count
    count = 0

    Invoice.includes(:buyer_account, :provider_account).find_each(:batch_size => 100) do |invoice|

      begin
        buyer = invoice.buyer
        provider = invoice.provider

        count += 1
        puts "Migrating #{invoice.id} (#{count}/#{all})"

        # just to skip master locally [if you have just one provider in the db
        next if (Rails.env.development? && provider.master?)

        if [ :pending, :unpaid, :cancelled, :failed, :paid ].include?(invoice.state.to_sym)
          invoice.vat_rate = buyer.vat_rate
          invoice.vat_code = buyer.vat_code || ''
          invoice.fiscal_code = invoice.fiscal_code || ''
          invoice.currency = invoice.provider.currency

          invoice.from_address_name = provider.org_name
          invoice.from_address_line1 = provider.org_legaladdress
          invoice.from_address_line2 = provider.org_legaladdress_cont
          invoice.from_address_city = provider.city
          invoice.from_address_state = provider.state
          invoice.from_address_region = provider.state_region
          invoice.from_address_country = provider.country.try!(:name)
          invoice.from_address_zip = provider.zip
          invoice.from_address_phone = provider.telephone_number

          invoice.to_address_name = buyer.org_name
          invoice.to_address_line1 = buyer.org_legaladdress
          invoice.to_address_line2 = buyer.org_legaladdress_cont
          invoice.to_address_city = buyer.city
          invoice.to_address_state = buyer.state
          invoice.to_address_region = buyer.state_region
          invoice.to_address_country = buyer.country.try!(:name)
          invoice.to_address_zip = buyer.zip
          invoice.to_address_phone = buyer.telephone_number
        end

        invoice.vat_rate = buyer.vat_rate
        invoice.save(false)
      rescue => e
        puts "Failed to migrate #{invoice.id}"
        puts e.message
        raise e
      end
    end

    # Zombies are invoices whose owner is dead but they are still
    # alive.
    #
    #
    # By 21th January 2013
    #  [8682, 23792, 25072, 38662, 47312, 264406, 265336, 481606, 566846, 673396, 753376, 988806, 1224236, 1495886, 1785646, 1840131, 2510010, 2689460, 2878210, 5000238, 5029528, 5047218, 5116818, 5553461, 5553601, 5554251, 5554312, 5554331, 5554341, 5555091, 5555341, 5555351, 5555501, 5555611, 5556371, 5556381, 5556552, 5556562, 5556742, 5557071, 5557081, 5557221, 5558251, 5558292, 5558312, 5558632, 5558642, 5558652, 5558662, 5558801, 5558852, 5558941, 5558992, 5559052, 5559062, 5559072, 5559102, 5559122, 5559201, 5560641, 5560951, 5561131, 5567082, 5567122, 5567161, 10146868, 10147158, 10151218, 10156728, 10241408, 11158678, 12190208, 13243488, 14303438, 15374698, 30006622, 278851896, 401452646, 426103396, 451981786, 478043016, 504052006, 533743916, 681787261, 681787362, 681787391, 681787411, 681787421, 681787451, 681787481, 681787491, 681787622, 681787741, 681789091, 681790481, 681790491, 681790501, 681790721, 681790982, 681791001, 681794081, 681794301]
    #
    def self.find_invoice_zombies
      ids = Invoice.connection.execute("select invoices.id from invoices join accounts on invoices.buyer_account_id = accounts.id where invoices.state in ('finalized', 'pending', 'open', 'unpaid') and accounts.deleted_at IS NOT NULL").map(&:first)

      puts "There are #{ids.count} zombies."
    end

  end
end
