# Integration Architecture Blueprint

## Goals
- Decouple external partnerships (SMS, payments, DNA, cultural archives) behind service interfaces.
- Allow multiple providers per capability with runtime selection via configuration.
- Centralize webhook handling, retries, and monitoring for partner integrations.

## Service Modules

| Module | Purpose | External Providers | Implementation Notes |
| --- | --- | --- | --- |
| `NotificationGateway` | Outbound SMS/email/WhatsApp | MTN, Vodafone, Twilio, WhatsApp Cloud | Use queue-backed jobs; provider drivers implement `sendMessage` and `sendTemplate`. Feature flags per region. |
| `BillingGateway` | Payments & subscriptions | Stripe, Paystack, Flutterwave | Mirrors `BillingProviderInterface` (see monetization MVP). Supports tokenization, invoices, refunds. |
| `GenealogyGateway` | DNA & heritage verification | MyHeritage, Ancestry API | Polling or webhook ingest. Store normalized lineage evidence in `heritage_records` table. |
| `MediaArchiveGateway` | Cultural/media ingestion | Museums, S3-compatible storage | Handle large uploads via pre-signed URLs. Metadata stored in `cultural_assets`. |
| `EventVendorsGateway` | Event services | Jumia Events, local planners | Sync vendor catalog, booking status, pricing updates. |

### Package Structure
```
app/
  Integrations/
    Contracts/ (interfaces)
    Notification/
      Providers/
        MtnSmsProvider.php
        VodafoneSmsProvider.php
    Billing/
      Providers/
        StripeBillingProvider.php
        PaystackBillingProvider.php
    ...
```

Each provider registered via service provider binding:
```php
$this->app->bind(NotificationProvider::class, function () {
    return match (config('services.notification.driver')) {
        'mtn' => new MtnSmsProvider(),
        'vodafone' => new VodafoneSmsProvider(),
        default => new TwilioSmsProvider(),
    };
});
```

## Configuration
- Extend `config/services.php` with sections for `notification`, `billing`, `genealogy`, `media_archive`, `event_vendors`.
- Environment variables for credentials, webhook secrets, and feature toggles.
- Add `integration.php` config to control retry backoff, circuit breaker thresholds, observability.

## Webhook & Callback Handling
- Single route group `/webhooks/{integration}` with signature verification.
- Store raw payloads in `integration_events` table (status: pending, processed, failed).
- Dispatch jobs per provider to process events; idempotency keys ensure safe replays.

## Retry & Circuit Breaker Strategy
- Jobs use exponential backoff up to configurable max attempts.
- Introduce `integration_failures` metric with alerts when threshold exceeded.
- Circuit breaker temporarily disables provider (switch to fallback driver) when error rate high.

## Observability
- Wrap provider calls with logging (request/response IDs) and metrics (latency, success rate).
- Emit events to `IntegrationEvent` model for audit trails.
- Integrate with Laravel Telescope/Octane or custom middleware for tracing.

## Security & Compliance
- Secrets stored in `.env` or secret manager (future). No credentials committed.
- Encrypt stored tokens with Laravel's encryption helper.
- Apply rate limiting and signature validation on inbound webhooks.
- Maintain data residency awareness—configure providers per tenant/region where necessary.

## Next Steps
1. Scaffold `app/Integrations` directory with base contracts and service providers.
2. Implement SMS driver (MTN) MVP for invitations with queue + retry logic.
3. Implement Stripe billing driver in tandem with subscription MVP.
4. Define webhook controllers + `integration_events` migration.
5. Add monitoring and alerting hooks (eg. to Slack/email) for failure thresholds.
