Bug: [BUG] Bug in merchant connector account create - delete flows



### Bug Description

There is a problem with how the `configs` table is updated. The problem arises when a user deletes a connector and then adds the same one, the config isn't cleaned from the connector when it's deleted, and the new connector (with the same type) is appended to the array.
It looks something like this:
```json
[{"connector":"adyen","merchant_connector_id":"mca_123XXX"}, //old one, already deleted
{"connector":"adyen","merchant_connector_id":"mca_456XXX"}] //new one
``` 
When a payment (or payout or anything else connector related) is being created the router looks at the first occurrence of the connector (which is already deleted) and then looks at the `merchant_connector_account` table for an already deleted `merchant_connector_id`, unsurprisingly does not find it and throws an error. Affects both payment and payout processors


### Expected Behavior

I think either the payment connector delete function should clean the config array of the deleted connector, or the update function should prepend the config instead of appending. 

### Actual Behavior

The delete function does not clean the config and then just appends it when new creator of same type is added

### Steps To Reproduce

To reproduce: 
1. Create a merchant connector account of any type
2. Delete it
3. Create the same connector 
4. Try to make a payment with that connector
5. Get error 404:
```json
{
    "error": {
        "type": "invalid_request",
        "message": "Merchant connector account does not exist in our records",
        "code": "HE_02",
        "reason": "mca_123XXX does not exist"
    }
}
```

### Context For The Bug

Trace for update config:

```sh
at crates/diesel_models/src/query/generics.rs:247
    in router::db::configs::update_config_in_database
    in storage_impl::redis::cache::publish_and_redact
    in router::db::configs::update_config_by_key
    in core::routing::helpers::update_merchant_default_config
    in router::core::retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists
```


### Environment

Are you using hyperswitch hosted version? No

If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution: Ubuntu 22.04
2. Rust version (output of `rustc --version`): `rustc 1.80.1 (3f5fd8dd4 2024-08-06)`
3. App version (output of `cargo r --features vergen -- --version`): `2024.08.27` (not running the latest version but checked the functions responsible and there weren't any changes)


### Have you spent some time checking if this bug has been raised before?

- [x] I checked and didn't find a similar issue

### Have you read the Contributing Guidelines?

- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)

### Are you willing to submit a PR?

Yes, I am willing to submit a PR!
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 781b5e3710a..f0adf49c1e8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3327,6 +3327,16 @@ pub enum PresenceOfCustomerDuringPayment {
     Absent,
 }
 
+impl From<ConnectorType> for TransactionType {
+    fn from(connector_type: ConnectorType) -> Self {
+        match connector_type {
+            #[cfg(feature = "payouts")]
+            ConnectorType::PayoutProcessor => Self::Payout,
+            _ => Self::Payment,
+        }
+    }
+}
+
 #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)]
 pub enum TaxCalculationOverride {
     /// Skip calling the external tax provider
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 055c428b1fb..26a3be0863c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1931,6 +1931,65 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
         }
         Ok(())
     }
+
+    async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
+        &self,
+    ) -> RouterResult<()> {
+        let mut default_routing_config = routing::helpers::get_merchant_default_config(
+            self.store,
+            self.merchant_id.get_string_repr(),
+            self.transaction_type,
+        )
+        .await?;
+
+        let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
+            self.store,
+            self.profile_id.get_string_repr(),
+            self.transaction_type,
+        )
+        .await?;
+
+        if let Some(routable_connector_val) = self.routable_connector {
+            let choice = routing_types::RoutableConnectorChoice {
+                choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+                connector: *routable_connector_val,
+                merchant_connector_id: Some(self.merchant_connector_id.clone()),
+            };
+            if default_routing_config.contains(&choice) {
+                default_routing_config.retain(|mca| {
+                    mca.merchant_connector_id
+                        .as_ref()
+                        .map_or(true, |merchant_connector_id| {
+                            merchant_connector_id != self.merchant_connector_id
+                        })
+                });
+                routing::helpers::update_merchant_default_config(
+                    self.store,
+                    self.merchant_id.get_string_repr(),
+                    default_routing_config.clone(),
+                    self.transaction_type,
+                )
+                .await?;
+            }
+            if default_routing_config_for_profile.contains(&choice.clone()) {
+                default_routing_config_for_profile.retain(|mca| {
+                    mca.merchant_connector_id
+                        .as_ref()
+                        .map_or(true, |merchant_connector_id| {
+                            merchant_connector_id != self.merchant_connector_id
+                        })
+                });
+                routing::helpers::update_merchant_default_config(
+                    self.store,
+                    self.profile_id.get_string_repr(),
+                    default_routing_config_for_profile.clone(),
+                    self.transaction_type,
+                )
+                .await?;
+            }
+        }
+        Ok(())
+    }
 }
 #[cfg(feature = "v2")]
 struct DefaultFallbackRoutingConfigUpdate<'a> {
@@ -1970,6 +2029,40 @@ impl<'a> DefaultFallbackRoutingConfigUpdate<'a> {
         }
         Ok(())
     }
+
+    async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
+        &self,
+    ) -> RouterResult<()> {
+        let profile_wrapper = ProfileWrapper::new(self.business_profile.clone());
+        let default_routing_config_for_profile =
+            &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
+        if let Some(routable_connector_val) = self.routable_connector {
+            let choice = routing_types::RoutableConnectorChoice {
+                choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+                connector: *routable_connector_val,
+                merchant_connector_id: Some(self.merchant_connector_id.clone()),
+            };
+            if default_routing_config_for_profile.contains(&choice.clone()) {
+                default_routing_config_for_profile.retain(|mca| {
+                    mca.merchant_connector_id
+                        .as_ref()
+                        .map_or(true, |merchant_connector_id| {
+                            merchant_connector_id != self.merchant_connector_id
+                        })
+                });
+
+                profile_wrapper
+                    .update_default_fallback_routing_of_connectors_under_profile(
+                        self.store,
+                        default_routing_config_for_profile,
+                        self.key_manager_state,
+                        &self.key_store,
+                    )
+                    .await?
+            }
+        }
+        Ok(())
+    }
 }
 #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
 #[async_trait::async_trait]
@@ -3139,7 +3232,7 @@ pub async fn delete_connector(
         .await
         .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
 
-    let _mca = db
+    let mca = db
         .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
             key_manager_state,
             &merchant_id,
@@ -3161,6 +3254,26 @@ pub async fn delete_connector(
             id: merchant_connector_id.get_string_repr().to_string(),
         })?;
 
+    // delete the mca from the config as well
+    let merchant_default_config_delete = MerchantDefaultConfigUpdate {
+        routable_connector: &Some(
+            common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
+                errors::ApiErrorResponse::InvalidDataValue {
+                    field_name: "connector_name",
+                }
+            })?,
+        ),
+        merchant_connector_id: &mca.get_id(),
+        store: db,
+        merchant_id: &merchant_id,
+        profile_id: &mca.profile_id,
+        transaction_type: &mca.connector_type.into(),
+    };
+
+    merchant_default_config_delete
+        .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
+        .await?;
+
     let response = api::MerchantConnectorDeleteResponse {
         merchant_id,
         merchant_connector_id,
@@ -3207,6 +3320,32 @@ pub async fn delete_connector(
             id: id.clone().get_string_repr().to_string(),
         })?;
 
+    let business_profile = db
+        .find_business_profile_by_profile_id(key_manager_state, &key_store, &mca.profile_id)
+        .await
+        .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
+            id: mca.profile_id.get_string_repr().to_owned(),
+        })?;
+
+    let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate {
+        routable_connector: &Some(
+            common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
+                errors::ApiErrorResponse::InvalidDataValue {
+                    field_name: "connector_name",
+                }
+            })?,
+        ),
+        merchant_connector_id: &mca.get_id(),
+        store: db,
+        business_profile,
+        key_store,
+        key_manager_state,
+    };
+
+    merchant_default_config_delete
+        .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
+        .await?;
+
     let response = api::MerchantConnectorDeleteResponse {
         merchant_id: merchant_id.clone(),
         id,

## Type of Change
<!-- Put an `x` in the boxes that apply -->

- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD

## Description
Fixes #5966 (in both v1 and v2). Now the router cleans up the configs table (or business_profile in v2) when a connector is deleted.


### Additional Changes

- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables

<!--
Provide links to the files with corresponding changes.

Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->


## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.

If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->


## How did you test it?
Added a payment and payout processor, checked if values are present in config, deleted and rechecked.
v1:
![v1test](https://github.com/user-attachments/assets/fad9e25a-edc0-4bdd-9835-e577c1d43d05)

v2:
![v2test](https://github.com/user-attachments/assets/2e6f311b-c860-407a-9c61-8162c77f6ec8)


## Test on Integ
- Create any 2 MCA's
```
curl --location 'http://localhost:8080/account/merchant_1733401776/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
    "connector_type": "payment_processor",
    "connector_name": "stripe",
    "connector_account_details": {
        "auth_type": "HeaderKey",
        "api_key": "{{api_key}}"
    },
     "connector_label": "stripe_US_default7777",
    "test_mode": false,
    "disabled": false,
    "payment_methods_enabled": [
        {
            "payment_method": "card",
            "payment_method_types": [
                {
                    "payment_method_type": "credit",
                    "card_networks": [
                        "Visa"
                    ],
                    "minimum_amount": 1,
                    "maximum_amount": 200000,
                    "recurring_enabled": false,
                    "installment_payment_enabled": false
                },
                {
                    "payment_method_type": "debit",
                    "card_networks": [
                        "JCB"
                    ],
                    "minimum_amount": 1,
                    "maximum_amount": 200000,
                    "recurring_enabled": false,
                    "installment_payment_enabled": false
                }
            ]
        },
        {
            "payment_method": "wallet",
            "payment_method_types": [
                {
                    "payment_method_type": "google_pay",
                    "payment_experience": "invoke_sdk_client",
                    "card_networks": null,
                    "minimum_amount": 1,
                    "maximum_amount": 50000,
                    "recurring_enabled": false,
                    "installment_payment_enabled": false
                },
                {
                    "payment_method_type": "apple_pay",
                    "payment_experience": "invoke_sdk_client",
                    "card_networks": null,
                    "minimum_amount": 600,
                    "maximum_amount": 800,
                    "recurring_enabled": false,
                    "installment_payment_enabled": false
                }
            ]
        },
        {
            "payment_method": "pay_later",
            "payment_method_types": [
                {
                    "payment_method_type": "affirm",
                    "payment_experience": "redirect_to_url",
                    "card_networks": null,
                    "minimum_amount": 1,
                    "maximum_amount": 50000,
                    "recurring_enabled": false,
                    "installment_payment_enabled": false
                }
            ]
        }
    ],
    "metadata": {
        "city": "NY",
        "unit": "245"
    }
    
        
}'
```
- Do the list for default fallback routing connectors, the connector should be present
```
curl --location 'http://localhost:8080/routing/default/profile' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \
--data ''
```
- Delete the one of those 2 MCA's
```
curl --location --request DELETE 'http://localhost:8080/account/merchant_1733401776/connectors/mca_jIEg3gZxzs54aMMrhT9D' \
--header 'Accept: application/json' \
--header 'api-key: test_admin'
```
- The list for default fallback routing connectors, the connector shouldn't be present
```
curl --location 'http://localhost:8080/routing/default/profile' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \
--data ''
```

## Checklist
<!-- Put an `x` in the boxes that apply -->

- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
