namespace :db do
  namespace :billing do
    desc "Sync billing to 4D"
    task :sync => :environment do
      Current.user = User.admin.first
      abort 'No superadmin user in the system. Please add superadmin user and try again.' unless Current.user

      Current.host = Rails.application.config.action_mailer.default_url_options[:host]
      abort 'No default_url_options in the system. Please put default_url_options and try again.' unless Current.host
      abort 'No Pixtech instance in the system. Please add Pixtech instance and try again.' unless Pixtech.instance

      Billing.where(synced_to_4d: false).find_each do |billing|
        begin
          Pixpalace::ClientsResource.sync!(billing.billing_company, create_only: true)
          Pixpalace::InvoiceResource.sync!(billing)
          billing.update_columns(synced_to_4d: true)
        rescue Exception => e
          Pixpalace::ResourceMailer.error(I18n.t('billing', locale: :fr), e, { id: billing.id, number: billing.full_number }).deliver_now
        end
      end
    end
  end
end
