import { Controller, Post, Body, Logger, Headers, HttpException } from '@nestjs/common'; import { PlatformGraphqlService } from '../platform/platform-graphql.service'; import { AiEnrichmentService } from '../ai/ai-enrichment.service'; @Controller('api/call') export class CallLookupController { private readonly logger = new Logger(CallLookupController.name); constructor( private readonly platform: PlatformGraphqlService, private readonly ai: AiEnrichmentService, ) {} @Post('lookup') async lookupCaller( @Body() body: { phoneNumber: string }, @Headers('authorization') authHeader: string, ) { if (!authHeader) throw new HttpException('Authorization required', 401); if (!body.phoneNumber) throw new HttpException('phoneNumber required', 400); const phone = body.phoneNumber.replace(/^0+/, ''); this.logger.log(`Looking up caller: ${phone}`); // Query platform for leads matching this phone number let lead = null; let activities: any[] = []; try { lead = await this.platform.findLeadByPhoneWithToken(phone, authHeader); } catch (err) { this.logger.warn(`Lead lookup failed: ${err}`); } if (lead) { this.logger.log(`Matched lead: ${lead.id} — ${lead.contactName?.firstName} ${lead.contactName?.lastName}`); // Get recent activities try { activities = await this.platform.getLeadActivitiesWithToken(lead.id, authHeader, 5); } catch (err) { this.logger.warn(`Activity fetch failed: ${err}`); } // AI enrichment if no existing summary if (!lead.aiSummary) { try { const enrichment = await this.ai.enrichLead({ firstName: lead.contactName?.firstName, lastName: lead.contactName?.lastName, leadSource: lead.leadSource ?? undefined, interestedService: lead.interestedService ?? undefined, leadStatus: lead.leadStatus ?? undefined, contactAttempts: lead.contactAttempts ?? undefined, createdAt: lead.createdAt, activities: activities.map((a: any) => ({ activityType: a.activityType ?? '', summary: a.summary ?? '', })), }); lead.aiSummary = enrichment.aiSummary; lead.aiSuggestedAction = enrichment.aiSuggestedAction; // Persist AI enrichment back to platform try { await this.platform.updateLeadWithToken(lead.id, { aiSummary: enrichment.aiSummary, aiSuggestedAction: enrichment.aiSuggestedAction, }, authHeader); } catch (err) { this.logger.warn(`Failed to persist AI enrichment: ${err}`); } } catch (err) { this.logger.warn(`AI enrichment failed: ${err}`); } } } else { this.logger.log(`No lead found for phone ${phone}`); } return { lead, activities, matched: lead !== null, }; } }