# Implementation Guide for Notification Microservice

## Reference Document
**Primary Specification**: `docs/final-specification.md` - This is the single source of truth. Follow it strictly.

---

## Core Principles

1. **Multi-Tenancy First**: Every entity MUST include `projectId`. All queries MUST be project-scoped.
2. **Project Isolation**: Data from one project must NEVER be accessible by another project.
3. **Context-Based Scoping**: Use API key authentication to automatically set project context (Option B from spec).
4. **Security**: Hash all secrets (API keys, passwords). Validate all inputs. Use parameterized queries.

---

## Implementation Order (Follow Spec Section 22)

### Phase 1: Foundation (Weeks 1-2)
1. Initialize NestJS project with TypeScript strict mode
2. Set up TypeORM + MySQL, Redis, BullMQ
3. Create **Project** entity (Section 4.1) - Foundation of multi-tenancy
4. Create **PlatformAdmin** entity (Section 4.11)
5. Implement API key authentication (Section 6.1, Option A - single key per project)
6. Create ProjectContextService to manage project context
7. Implement ApiKeyGuard and ProjectGuard (Section 6.4)
8. Create base repository with automatic projectId filtering

**Critical**: Test project isolation before proceeding. Verify queries cannot access other projects' data.

### Phase 2: Core Entities (Week 2-3)
9. Create all entities from Section 4 with `projectId` foreign keys:
   - User (4.3), Role (4.4), Rule (4.5), Event (4.6), Notification (4.7)
   - AuditLog (4.8), TransferBucket (4.9), Sound (4.13)
10. Create database migrations with proper indexes (composite indexes including projectId)
11. Add unique constraints: `(projectId, email)`, `(projectId, name)` for roles, etc.

### Phase 3: Authentication & Authorization (Week 3)
12. Implement JWT authentication (Section 6.2) with projectId in token payload
13. Create JwtAuthGuard, RolesGuard (Section 6.4)
14. Implement user registration/login (Section 5.4) - project-scoped
15. Create decorators: @CurrentUser(), @CurrentProject(), @Roles()

### Phase 4: Core Modules (Weeks 4-5)
16. **Rules Module** (Section 5.6):
    - Implement RuleEngineService (Section 10.1) using `expr-eval`
    - CRUD endpoints with project scoping
    - Test rule evaluation thoroughly
17. **Events Module** (Section 5.3):
    - POST /api/v1/events with API key auth
    - Quota checking before processing
    - Redis Streams integration (project-scoped: `project:{projectId}:events`)
    - Event processing queue
18. **Notifications Module** (Section 5.7):
    - Notification creation after rule evaluation
    - PusherService (Section 10.3) with project-specific credentials
    - NotificationDeliveryService (Section 10.2)
    - Push notification queue (stub FCM/APNs initially)

### Phase 5: Supporting Modules (Week 6)
19. Users, Roles, TransferBuckets, Sounds modules (Sections 5.5, 5.8, 5.10, 5.11)
20. Audit logging (Section 5.9) - log all critical actions with projectId
21. Health checks and status endpoints (Section 5.12)

### Phase 6: Advanced Features (Weeks 7-12)
22. Usage tracking and quotas (Section 14)
23. Webhooks (Section 15)
24. Billing integration (Stripe) - Phase 5
25. Analytics and reporting
26. Mobile SDK - Phase 6

---

## Coding Standards

### Project Isolation
```typescript
// ✅ CORRECT: Always filter by projectId
async findUserById(id: string, projectId: string) {
  return this.userRepository.findOne({ 
    where: { id, projectId } // Always include projectId
  });
}

// ❌ WRONG: Missing projectId filter
async findUserById(id: string) {
  return this.userRepository.findOne({ where: { id } });
}
```

### Repository Pattern
```typescript
// Use base repository with automatic project filtering
class BaseRepository<T> {
  findOne(options: FindOptions<T>) {
    const projectId = this.projectContext.getProjectId();
    return this.repository.findOne({
      ...options,
      where: { ...options.where, projectId }
    });
  }
}
```

### API Key Authentication
```typescript
// ApiKeyGuard must:
// 1. Extract X-API-Key and X-API-Secret from headers
// 2. Hash secret and lookup project
// 3. Verify project status is 'active'
// 4. Set project context via ProjectContextService
// 5. Check quotas before allowing request
```

### Error Handling
```typescript
// Always include project context in errors (but don't leak sensitive data)
throw new NotFoundException('Resource not found'); // Don't reveal projectId in error
// But log projectId internally for debugging
this.logger.error('Resource not found', { resourceId, projectId });
```

### Validation
- Use `class-validator` decorators on all DTOs
- Validate condition DSL syntax in RuleEngineService
- Sanitize all user inputs
- Validate projectId matches authenticated project

---

## Testing Requirements

1. **Project Isolation Tests**: Create 2 projects, verify data from Project A cannot be accessed by Project B
2. **Unit Tests**: All services with mocked project context
3. **Integration Tests**: All endpoints with project scoping
4. **E2E Tests**: Complete flows (event → rule → notification → delivery)

---

## Common Pitfalls to Avoid

1. ❌ Forgetting to add `projectId` to new entities
2. ❌ Queries without projectId filter
3. ❌ Using global Pusher credentials instead of project-specific
4. ❌ Cache keys without project prefix (`project:{projectId}:*`)
5. ❌ Queue jobs without projectId in job data
6. ❌ Error messages that leak project information
7. ❌ Missing quota checks on event ingestion
8. ❌ Not validating API key before processing requests

---

## Validation Checklist (Before Each Phase)

- [ ] All entities have `projectId` foreign key
- [ ] All queries include projectId filter
- [ ] All Redis keys prefixed with `project:{projectId}:`
- [ ] All queue jobs include projectId in data
- [ ] API key authentication sets project context
- [ ] JWT tokens include projectId
- [ ] Guards validate project access
- [ ] Tests verify project isolation
- [ ] Error handling doesn't leak project info
- [ ] Quota checks implemented where required

---

## Quick Reference

- **Spec Document**: `docs/final-specification.md`
- **Data Models**: Section 4
- **API Endpoints**: Section 5
- **Authentication**: Section 6
- **Event Flow**: Section 7
- **Services**: Section 10
- **Implementation Priority**: Section 22

---

## When in Doubt

1. Check `final-specification.md` first
2. Ensure project isolation is maintained
3. Follow NestJS best practices (modules, services, guards, decorators)
4. Write tests for project isolation
5. Ask for clarification if spec is ambiguous

**Remember**: Multi-tenancy and project isolation are non-negotiable. Every feature must respect these principles.

