# Integration Endpoints

## Purpose
Document integration API endpoints for managing site integrations, testing connections, syncing, and handling WordPress webhooks.

## Code Locations (exact paths)
- Routing: `backend/igny8_core/modules/integration/urls.py`
- Views: `backend/igny8_core/modules/integration/views.py`
- Webhooks: `backend/igny8_core/modules/integration/webhooks.py`
- Services: `backend/igny8_core/business/integration/services/*`

## High-Level Responsibilities
- CRUD for `SiteIntegration` records.
- Test connections (detail and collection-level), trigger syncs, fetch sync status, update site structure, and sync WordPress content.
- Expose WordPress webhook endpoints for status/metadata updates.

## Detailed Behavior
- Base path: `/api/v1/integration/`
- Viewset: `IntegrationViewSet` (`/integrations/`, inherits `SiteSectorModelViewSet` but overrides queryset to filter by site_id since integrations have site only).
  - Permissions: `IsAuthenticatedAndActive`, `IsEditorOrAbove`; throttle scope `integration`.
  - Serializer exposes derived `api_key` (from credentials) and validates WordPress integrations require API key.
  - Actions:
    - `test_connection` (detail): calls `IntegrationService.test_connection` on existing integration; returns success/error.
    - `test_connection_collection` (POST `integrations/test-connection/`, AllowAny): accepts site_id/api_key/site_url; validates site ownership or matching `Site.wp_api_key`; creates integration if missing; tests WordPress connection; deletes integration on failure; returns integration_id on success.
    - `sync`: triggers `SyncService.sync` (direction metadata/both/to_external/from_external); metadata-only path uses `SyncMetadataService` internally.
    - `sync_status`: returns sync status from `SyncService`.
    - `update_site_structure`: updates `config_json.content_types` (post_types/taxonomies, plugin flags, timestamp) from WordPress push payload.
    - `get_content_types`: returns content type config from integration config.
    - `debug_status`: returns debug data via `SyncHealthService`.
    - `sync_wordpress_content`: calls `ContentSyncService.sync_from_wordpress` for a specific content_id.
- Webhooks:
  - `/webhooks/wordpress/status/` and `/webhooks/wordpress/metadata/` endpoints for WordPress callbacks (handled in `webhooks.py`).

## Data Structures / Models Involved (no code)
- `SiteIntegration`, `SyncEvent`, `Site`, `Account`.

## Execution Flow
- CRUD/test/sync requests → DRF auth → site-filtered queryset → service calls → model updates/sync actions. Collection-level test may create/delete integration based on result. Webhooks call handlers for incoming WordPress events.

## Cross-Module Interactions
- Integrations used by publishing/sync flows to external platforms; WordPress API key path relies on `Site.wp_api_key` and integration credentials.
- Sync services interact with writer/planner content for metadata/content sync.

## State Transitions
- Integration `sync_status/last_sync_at/is_active/sync_enabled` updated by sync/test actions; `SyncEvent` records per-action success/failure with timestamps and IDs.

## Error Handling
- Invalid site/auth/API key return 403/404/400; unsupported platforms raise `NotImplementedError`; failed collection-level tests delete newly created integrations.

## Tenancy Rules
- All endpoints scoped to the site/account; queryset filters by site_id and permissions enforce authenticated editor-or-above unless using collection-level API key path.

## Billing Rules
- None; integration endpoints do not change credits.

## Background Tasks / Schedulers
- None specific; sync logic executes in service calls (may delegate internally).

## Key Design Considerations
- Single integration per site+platform; collection-level test supports plugin onboarding with API key.
- Credentials stored as JSON (encryption pending).

## How Developers Should Work With This Module
- Use `IntegrationService` for CRUD/test; extend platform support via new test logic and serializer validation.
- Keep site scoping and API key validation intact for collection-level tests.

