# frozen_string_literal: true

class <%= class_name %>ConnectionCleanupJob < ApplicationJob
  queue_as :default
<% if investment_provider? -%>

  def perform(<%= file_name %>_item_id:, authorization_id:, account_id:)
    Rails.logger.info(
      "<%= class_name %>ConnectionCleanupJob - Cleaning up connection #{authorization_id} " \
      "for former account #{account_id}"
    )

    <%= file_name %>_item = <%= class_name %>Item.find_by(id: <%= file_name %>_item_id)
    return unless <%= file_name %>_item

    # Check if other accounts still use this connection
    if <%= file_name %>_item.<%= file_name %>_accounts
         .where(<%= file_name %>_authorization_id: authorization_id)
         .exists?
      Rails.logger.info("<%= class_name %>ConnectionCleanupJob - Connection still in use, skipping")
      return
    end

    # Delete from provider API
    delete_connection(<%= file_name %>_item, authorization_id)

    Rails.logger.info("<%= class_name %>ConnectionCleanupJob - Connection #{authorization_id} deleted")
  rescue => e
    Rails.logger.warn(
      "<%= class_name %>ConnectionCleanupJob - Failed: #{e.class} - #{e.message}"
    )
    # Don't raise - cleanup failures shouldn't block other operations
  end

  private

    def delete_connection(<%= file_name %>_item, authorization_id)
      provider = <%= file_name %>_item.<%= file_name %>_provider
      return unless provider

      credentials = <%= file_name %>_item.<%= file_name %>_credentials
      return unless credentials

      # TODO: Implement API call to delete connection
      # Example:
      # provider.delete_connection(
      #   authorization_id: authorization_id,
      #   **credentials
      # )
      nil # Placeholder until provider.delete_connection is implemented
    rescue => e
      Rails.logger.warn(
        "<%= class_name %>ConnectionCleanupJob - API delete failed: #{e.message}"
      )
    end
<% else -%>

  def perform(<%= file_name %>_item_id:, account_id:)
    Rails.logger.info(
      "<%= class_name %>ConnectionCleanupJob - Cleaning up for former account #{account_id}"
    )

    <%= file_name %>_item = <%= class_name %>Item.find_by(id: <%= file_name %>_item_id)
    return unless <%= file_name %>_item

    # For banking providers, cleanup is typically simpler since there's no
    # separate authorization concept - the item itself holds the credentials.
    # Override this method if your provider needs specific cleanup logic.

    Rails.logger.info("<%= class_name %>ConnectionCleanupJob - Cleanup complete for account #{account_id}")
  rescue => e
    Rails.logger.warn(
      "<%= class_name %>ConnectionCleanupJob - Failed: #{e.class} - #{e.message}"
    )
    # Don't raise - cleanup failures shouldn't block other operations
  end
<% end -%>
end
