# Troubleshooting

Common issues and their solutions for the Teams Phone CLI.

## Exit Codes

The CLI uses specific exit codes to indicate different types of errors:

| Code | Name | Description |
|------|------|-------------|
| 0 | Success | Operation completed successfully |
| 1 | General Error | Unexpected error or server-side issue |
| 2 | Authentication Error | Token missing, expired, or invalid |
| 3 | Authorization Error | Missing required permissions |
| 4 | Not Found | User, number, policy, or location not found |
| 5 | Validation Error | Invalid input parameters |
| 6 | Rate Limit | API throttling limit exceeded |
| 7 | Configuration Error | Config file missing or invalid |
| 8 | Contract Error | API response doesn't match expected schema |

Use exit codes in scripts to handle errors appropriately:

```bash
teams-phone users list
if [ $? -eq 4 ]; then
    echo "Resource not found"
fi
```

## Authentication Issues

### "Authentication error" (Exit Code 2)

**Symptoms:**
- "Access token expired"
- "Authentication failed"
- "No valid token found"

**Solutions:**

1. **Re-authenticate:**
   ```bash
   teams-phone auth login --force
   ```

2. **Check certificate (if using certificate auth):**
   - Verify the certificate file exists at the configured path
   - Ensure the certificate hasn't expired
   - Confirm the certificate's public key is uploaded to Azure AD

3. **Check client secret (if using client-secret auth):**
   ```bash
   # Verify environment variable is set
   echo $TEAMS_PHONE_CLIENT_SECRET
   ```

4. **Verify tenant configuration:**
   ```bash
   teams-phone tenants test
   ```

### "Certificate not found"

**Windows Certificate Store:**
- Verify the certificate is in `Cert:\CurrentUser\My`
- Check the thumbprint matches exactly (no spaces)
- Ensure the private key is accessible

**Certificate File:**
- Verify the file path in config is correct
- Check file permissions (must be readable)
- For PFX files, ensure password is correct

## Authorization Issues

### "Authorization error" (Exit Code 3)

**Symptoms:**
- "Insufficient privileges"
- "Access denied"
- "Missing required permissions"

**Solutions:**

1. **Verify API permissions in Azure AD:**

   Required Application permissions:
   - `TeamsUserConfiguration.Read.All`
   - `TeamsTelephoneNumber.Read.All`
   - `TeamsTelephoneNumber.ReadWrite.All`
   - `TeamsPolicyUserAssign.ReadWrite.All`
   - `User.Read.All`
   - `Directory.Read.All`
   - `RoleManagement.Read.Directory`
   - `GroupMember.Read.All`

2. **Grant admin consent:**
   - Azure Portal > App Registrations > Your App > API Permissions
   - Click "Grant admin consent for [tenant]"

3. **Assign Teams Administrator role:**
   - Azure Portal > Microsoft Entra ID > Roles and administrators
   - Search "Teams Administrator"
   - Add your app's service principal

4. **Wait for propagation:**
   - Permission changes can take up to an hour to propagate
   - Re-authenticate after making changes: `teams-phone auth login --force`

## Resource Not Found (Exit Code 4)

### "User not found"

```bash
# Search for the user first
teams-phone users search "john"

# Verify UPN spelling
teams-phone users show john.doe@contoso.com
```

### "Phone number not found"

```bash
# List available numbers
teams-phone numbers list --status unassigned

# Search for the number
teams-phone numbers search "*1234"
```

### "Policy not found"

```bash
# List available policies
teams-phone policies list calling

# Check if CSV cache is up-to-date
# Re-export if needed (see scripts/README.md)
```

### "Location not found"

```bash
# Search locations
teams-phone locations search "Seattle"

# Update CSV cache if location was recently added
```

## Validation Errors (Exit Code 5)

### "Invalid phone number format"

Phone numbers should be in E.164 format:
- Correct: `+14255551234`
- Incorrect: `(425) 555-1234`, `425-555-1234`

### "E911 location required for Calling Plan numbers"

Calling Plan numbers require an emergency location:

```bash
# Specify location when assigning
teams-phone numbers assign user@contoso.com +14255551234 --location "Seattle HQ"
```

### "Number already assigned"

The number is assigned to another user. Unassign it first:

```bash
# Check current assignment
teams-phone numbers show +14255551234

# Unassign from current user
teams-phone numbers unassign +14255551234

# Assign to new user
teams-phone numbers assign newuser@contoso.com +14255551234 --location "Seattle HQ"
```

## Rate Limiting (Exit Code 6)

### "Rate limit exceeded"

The CLI automatically retries with exponential backoff (3 attempts) before failing.

**Solutions:**

1. **Wait and retry:**
   - Graph API throttling typically clears within minutes
   - For bulk operations, consider adding delays

2. **Reduce request rate:**
   - Use `--limit` to fetch fewer results per request
   - Space out bulk operations

3. **Check for other API consumers:**
   - Other applications using the same app registration share the quota

## Configuration Errors (Exit Code 7)

### "Configuration file not found"

Create the config directory and file:

```bash
mkdir -p ~/.teams-phone
teams-phone tenants add myorg "tenant-id" "client-id" --display-name "My Org"
```

### "Invalid configuration"

Check the config file syntax:

```bash
# View config file
cat ~/.teams-phone/config.toml

# Look for TOML syntax errors:
# - Missing quotes around strings
# - Invalid characters
# - Duplicate keys
```

### "Tenant not found"

The specified tenant profile doesn't exist:

```bash
# List configured tenants
teams-phone tenants list

# Add the missing tenant
teams-phone tenants add neworg "tenant-id" "client-id" --display-name "New Org"
```

## Contract Errors (Exit Code 8)

### "API contract validation failed"

The Graph API response doesn't match expected schema. This usually indicates:

1. **Microsoft updated their API:** Run `api-check` to validate:
   ```bash
   teams-phone api-check --verbose
   ```

2. **CLI version is outdated:** Update to the latest version:
   ```bash
   pip install --upgrade teams-phone-cli
   ```

3. **Bug in the CLI:** Report the issue with debug logs:
   ```bash
   teams-phone --debug-log /tmp/debug.log users list
   # Include /tmp/debug.log in your bug report
   ```

## CSV Cache Issues

### "CSV cache not found" or "Stale cache warning"

The CLI warns when CSV files are older than 30 days or missing.

**Solution:** Re-export using PowerShell:

```powershell
./scripts/Export-TeamsPhoneData.ps1 `
    -TenantId "..." `
    -ApplicationId "..." `
    -CertificateThumbprint "..."
```

See [scripts/README.md](../scripts/README.md) for full instructions.

### "Location/policy exists but not in cache"

The CSV cache is out of sync with Teams Admin Center.

1. Re-export the CSV data
2. Verify the export completed successfully
3. Check `~/.teams-phone/cache/export-metadata.json` for export timestamp

## Debug Logging

Enable detailed logging for troubleshooting:

```bash
# Write debug logs to file
teams-phone --debug-log ./debug.log users list

# View logs
cat ./debug.log
```

Debug logs include:
- API request/response details
- Cache hit/miss information
- Timing information
- Correlation IDs for tracking

**Note:** Debug logs never contain tokens, secrets, or full UPNs for security.

### Log Format

Debug logs are JSON Lines format:

```json
{"ts":"2026-01-24T10:30:00.123Z","correlation_id":"a1b2c3d4","level":"INFO","event":"command_start","command":"users list"}
{"ts":"2026-01-24T10:30:00.456Z","correlation_id":"a1b2c3d4","level":"DEBUG","event":"graph_request","method":"GET","endpoint":"/users"}
{"ts":"2026-01-24T10:30:01.012Z","correlation_id":"a1b2c3d4","level":"INFO","event":"command_complete","exit_code":0}
```

## Common Workflows

### Assigning a Number to a New User

```bash
# 1. Find the user
teams-phone users search "john"

# 2. Find an available number
teams-phone numbers list --status unassigned --type callingPlan

# 3. Find an emergency location
teams-phone locations search "Seattle"

# 4. Assign the number (dry-run first)
teams-phone numbers assign john@contoso.com +14255551234 --location "Seattle HQ" --dry-run

# 5. Execute the assignment
teams-phone numbers assign john@contoso.com +14255551234 --location "Seattle HQ"
```

### Bulk Operations

```bash
# 1. Validate CSV first
teams-phone numbers bulk-assign assignments.csv --dry-run

# 2. Execute with error handling
teams-phone numbers bulk-assign assignments.csv --continue-on-error -o results.csv

# 3. Review results
cat results.csv
```

### Switching Between Tenants

```bash
# Check current tenant
teams-phone tenants current

# List available tenants
teams-phone tenants list

# Switch tenant
teams-phone tenants switch fabrikam

# Or use --tenant flag for a single command
teams-phone -t fabrikam users list
```

## Getting Help

### Built-in Help

```bash
# Main help
teams-phone --help

# Command group help
teams-phone users --help

# Specific command help
teams-phone users list --help
```

### Reporting Issues

When reporting issues, include:

1. CLI version: `teams-phone --version`
2. Python version: `python --version`
3. Operating system
4. Full command that failed
5. Error message (with `--verbose` output if available)
6. Debug log (sanitize any sensitive information)

Report issues at: https://github.com/hvkc/teams-phone/issues
