# Integration Module Documentation

## Database Schema

### Tables: frm_integration_config
```sql
-- Integration configuration storage (merged from frm_communication_config, communication_config_type & communication_hub)
CREATE TABLE frm_integration_config (
    id INT AUTO_INCREMENT PRIMARY KEY,
    app_code VARCHAR(100) NOT NULL,
    integration_type VARCHAR(20) NOT NULL, -- EMAIL, SMS, WA, TELEPHONE
    integration_provider VARCHAR(100) NOT NULL, -- gmail, outlook, twilio, whatsapp, etc.
    integration_source_id INT NOT NULL, -- Integration source identifier
    level_id INT NOT NULL, -- Level to which this config applies
    level_type VARCHAR(100) NOT NULL, -- 'organization', 'department', 'user', 'project'
    status int DEFAULT 1, -- 1=active, 0=inactive
    priority INT DEFAULT 1, -- Lower number = higher priority
    is_default BOOLEAN DEFAULT FALSE, -- Whether this is the default config for this level+type
    config_json JSON NOT NULL,
    created_at timestamp DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_level_status (level_id, level_type, status),
    INDEX idx_type_provider (integration_type, integration_provider)
);

-- Integration source master table (existing)
CREATE TABLE frm_integration_master (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    logo VARCHAR(100),
    base_url VARCHAR(100),
    integration_type VARCHAR(20),
    status VARCHAR(100),
    -- ... other BaseEntity fields
);
```

## Architecture: Hierarchical Factory Pattern

### Strategy Interface
```ts
export interface IntegrationStrategy {
  sendMessage(to: string, message: string, config: any): Promise<any>;
}
```

### Factory Structure (Integration Type → Provider)
- **EMAIL**: gmail, outlook, aws-ses, sendgrid, generic
- **SMS**: twilio, knowlarity
- **WA**: whatsapp
- **TELEPHONE**: knowlarity

### Main Factory
```ts
@Injectable()
export class IntegrationFactory {
  create(integration_type: string, integration_provider: string): IntegrationStrategy {
    // Returns appropriate strategy instance
  }
  
  getAllSupportedCombinations(): Array<{integration_type, integration_provider}> {}
  getSupportedCombinationsForType(integration_type: string): Array<{integration_provider}> {}
  validateCombination(integration_type: string, integration_provider: string): boolean {}
}
```

### Service Layer
```ts
@Injectable()
export class IntegrationService {
  // Main send with fallback
  async send(orgId: number, to: string, message: string, type?: string, options: any = {}) {}
  
  // Type-specific methods
  async sendEmail(orgId: number, to: string, subject: string, body: string, attachments?: any[]) {}
  async sendSMS(orgId: number, to: string, message: string) {}
  async sendWhatsApp(orgId: number, to: string, message: string, mediaUrl?: string) {}
  
  // Bulk & template support
  async sendBulk(orgId: number, recipients: string[], message: string, type?: string) {}
  async sendWithTemplate(orgId: number, to: string, templateId: string, variables: any) {}
  
  // Configuration management
  async createConfiguration(orgId: number, configData: any) {}
  async updateConfiguration(hubId: number, configData: any) {}
  async setDefaultProvider(hubId: number) {}
}
```

## Provider Configuration Examples

### Gmail API
```json
{
  "app_code": "MYAPP",
  "integration_type": "EMAIL", 
  "integration_provider": "gmail",
  "integration_source_id": 1,
  "config_json": {
    "clientId": "your-client-id.apps.googleusercontent.com",
    "clientSecret": "your-client-secret", 
    "refreshToken": "your-refresh-token",
    "accessToken": "your-access-token"
  }
}
```

### Gmail SMTP
```json
{
  "app_code": "MYAPP",
  "integration_type": "EMAIL", 
  "integration_provider": "gmail",
  "integration_source_id": 1,
  "config_json": {
    "email": "your-email@gmail.com",
    "password": "your-app-password",
    "subject": "Default Subject"
  }
}
```

### Twilio SMS
```json
{
  "app_code": "MYAPP",
  "integration_type": "SMS", 
  "integration_provider": "twilio",
  "integration_source_id": 2,
  "config_json": {
    "accountSid": "your-twilio-account-sid",
    "authToken": "your-twilio-auth-token", 
    "fromNumber": "+1234567890"
  }
}
```

### WhatsApp Cloud API
```json
{
  "app_code": "MYAPP",
  "integration_type": "WA",
  "integration_provider": "whatsapp",
  "integration_source_id": 3,
  "config_json": {
    "accessToken": "your-whatsapp-access-token",
    "phoneNumberId": "your-phone-number-id",
    "apiVersion": "v17.0"
  }
}
```

### Gupshup WhatsApp
```json
{
  "app_code": "MYAPP",
  "integration_type": "WA",
  "integration_provider": "gupshup",
  "integration_source_id": 4,
  "config_json": {
    "apiKey": "your-gupshup-api-key",
    "appName": "your-app-name",
    "sourceNumber": "your-source-number",
    "baseUrl": "https://api.gupshup.io/sm/api/v1"
  }
}
```

**Gupshup Message Types:**
- **Text Message**: Default type, just send message
- **Template**: Requires `messageType: "template"`, `templateId`, optional `templateParams`
- **Image**: Requires `messageType: "image"`, `mediaUrl`, optional `previewUrl`, `caption`
- **Document**: Requires `messageType: "document"`, `mediaUrl`, optional `filename`, `caption`
- **Audio**: Requires `messageType: "audio"`, `mediaUrl`
- **Video**: Requires `messageType: "video"`, `mediaUrl`, optional `caption`
- **Location**: Requires `messageType: "location"`, `latitude`, `longitude`, optional `locationName`, `locationAddress`
- **List**: Requires `messageType: "list"`, `listItems`, optional `listTitle`, `globalButtons`
- **Quick Reply**: Requires `messageType: "quick_reply"`, `quickReplyOptions`

### Tubelight WhatsApp
```json
{
  "app_code": "MYAPP",
  "integration_type": "WA",
  "integration_provider": "tubelight",
  "integration_source_id": 5,
  "config_json": {
    "userName": "your-tubelight-username",
    "password": "your-tubelight-password",
    "tenantId": "your-tenant-id",
    "sourceNumber": "your-source-number",
    "baseUrl": "https://portal.tubelightcommunications.com/whatsapp/api/v1"
  }
}
```

**Tubelight Message Types:**
- **Text Message**: Default type with `messageType: "TEXT"` or no messageType specified
- **Template**: Requires `messageType: "template"`, `templateId`, optional `templateParams`, `templateLanguage` (default: "en")
- **Image**: Requires `messageType: "image"`, `mediaUrl`, optional `caption`
- **Document**: Requires `messageType: "document"`, `mediaUrl`, optional `filename`, `caption`
- **Audio**: Requires `messageType: "audio"`, `mediaUrl`
- **Video**: Requires `messageType: "video"`, `mediaUrl`, optional `caption`
- **Location**: Requires `messageType: "location"`, `latitude`, `longitude`, optional `locationName`, `locationAddress`
- **Interactive**: Requires `messageType: "interactive"`, `interactiveType` ("button" or "list"), optional `buttons`, `sections`, `header`, `footer`

### Knowlarity Voice
```json
{
  "app_code": "MYAPP",
  "integration_type": "TELEPHONE", 
  "integration_provider": "knowlarity",
  "integration_source_id": 4,
  "config_json": {
    "apiKey": "your-knowlarity-api-key",
    "apiSecret": "your-knowlarity-api-secret",
    "callerNumber": "your-knowlarity-number",
    "callType": "voice",
    "language": "en"
  }
}
```

## API Endpoints

```
POST /integration/send
POST /integration/config
GET /integration/level/:id/:type/configs
POST /integration/gmail/oauth/init
POST /integration/oauth/callback/gmail
```

## Module Structure
```
src/module/integration/
├── controller/integration.controller.ts
├── entity/integration-config.entity.ts
├── entity/integration-source.entity.ts
├── service/integration.service.ts
├── factories/integration.factory.ts
├── strategies/gmail.strategy.ts (and others)
└── integration.module.ts
```

## Level Hierarchy (fallback order)
1. **user** (highest priority)
2. **team** 
3. **project**
4. **department**
5. **organization** (lowest priority)