require "net/http"
require "uri"
require "json"

namespace :fdms do

  desc "Open Day"
  task :open_day => :environment do 
		DayActivity.open_day
  end

  desc "Post invoice to FDMS"
  task :post_invoice => :environment do 
		transaction = Transaction.includes(:customer_account_invoices, :customer_account).find(33625)
		InvoicePusher.call(transaction)
  end

  desc "Post invoice to FDMS"
  task :post_credit_note => :environment do 
		transaction = Transaction.includes(:customer_account_invoices, :customer_account).find(33625)
		notes = "Customer refunded"
		CreditNotePusher.call(transaction,notes)
  end

  desc "Close Day"
  task :close_day => :environment do 
		DayActivity.close_day
  end

  # define accounts to be fiscalised based on the receipts fiscalised
  task :define_accounts_to_fiscalise => :environment do
    invoices = Transaction.where(
      "transaction_type_id = 3 AND invoice_number IS NOT NULL AND deleted = false AND posted = false"
    )

    i = 0
    user = User.first

    invoices
      .group(:customer_account_id)
      .count
      .sort_by { |_, count| -count }
      .each do |customer_account_id, count|

        account = CustomerAccount.find(customer_account_id)

        puts "#{i += 1}. Customer Account: #{account.property_number} (#{count} invoices)"

        integrated_account = IntegratedCustomerAccount.find_or_initialize_by(
          customer_account_id: customer_account_id
        )

        if integrated_account.new_record?
          integrated_account.customer_account = account
          integrated_account.integration_date = account.registration_date
          integrated_account.user_id = user 
          integrated_account.property_number = account.property_number
          integrated_account.project_id = account.project_id
          integrated_account.class_category_id = account.class_category_id
          integrated_account.purchase_price = account.stand_value
          integrated_account.deposit_amount = account.deposit_amount
          integrated_account.size = account&.stand&.size
          integrated_account.status = account.status 
          integrated_account.active = true
          integrated_account.save!
          puts "  -> IntegratedAccount created"
        else
          puts "  -> IntegratedAccount already exists"
        end
      end
  end

end