module Users
  module DonationManipulator
    extend ActiveSupport::Concern

    def can_view_donations?
      super_admin?
    end

    def can_create_donations?
      super_admin?
    end

    def can_delete_and_restore_donations?
      super_admin?
    end

    def can_delete_closed_donations?
      super_admin?
    end

    def can_delete_closed_donation?(donation)
      super_admin? && donation.closed? && !donation.zero_affected_items?
    end

    def can_close_donations?
      super_admin?
    end

    def can_sync_donations?
      super_admin?
    end

    def can_sync_donation?(donation)
      can_sync_donations? && donation.can_be_synced?
    end

    def create_donation(params)
      transaction do
        raise PermissionError unless can_create_donations?
        donor = NetSuiteIntegration::DonorExporter.find_or_create_and_export(params)
        Donation.create_donation!(self, donor, params)
      end
    end

    def update_donation(params)
      transaction do
        raise PermissionError unless can_create_donations?
        donation = Donation.active_with_includes.find(params[:id])
        raise PermissionError unless can_view_donation?(donation)
        donation.update_donation!(params)
      end
    end

    def sync_donation(params)
      transaction do
        donation = Donation.find(params[:id])
        raise "Donation cannot be synced until donor is synced" unless donation.donor.synced?
        raise PermissionError unless can_sync_donation?(donation)
        NetSuiteIntegration::DonationExporter.new(donation).export_later
        donation
      end
    end

    def can_view_donation?(_donation)
      super_admin?
    end
  end
end
