import { NextResponse } from "next/server" import { fetchMutation, fetchQuery } from "convex/nextjs" import { api } from "@/convex/_generated/api" import { requirePhoneAgentInternalAuth } from "@/app/api/internal/phone-calls/shared" import { normalizePhoneE164 } from "@/lib/phone-normalization" export async function POST(request: Request) { const authError = await requirePhoneAgentInternalAuth(request) if (authError) { return authError } try { const body = await request.json() let metadata: Record = {} if (typeof body.metadata === "string" && body.metadata.trim()) { try { metadata = JSON.parse(body.metadata) } catch { metadata = {} } } const callerPhone = normalizePhoneE164( metadata.participantPhone || body.participantIdentity ) const contactContext = callerPhone ? await fetchQuery(api.voiceSessions.getPhoneAgentContextByPhone, { normalizedPhone: callerPhone, }) : null const result = await fetchMutation( api.voiceSessions.upsertPhoneCallSession, { roomName: String(body.roomName || ""), participantIdentity: String(body.participantIdentity || ""), callerPhone: callerPhone || undefined, siteUrl: body.siteUrl ? String(body.siteUrl) : undefined, pathname: body.pathname ? String(body.pathname) : undefined, pageUrl: body.pageUrl ? String(body.pageUrl) : undefined, source: "phone-agent", metadata: body.metadata ? String(body.metadata) : undefined, contactProfileId: contactContext?.contactProfile?.id, contactDisplayName: contactContext?.contactProfile?.displayName || (contactContext?.recentLead ? `${contactContext.recentLead.firstName} ${contactContext.recentLead.lastName}`.trim() : undefined), contactCompany: contactContext?.contactProfile?.company || contactContext?.recentLead?.company || undefined, startedAt: typeof body.startedAt === "number" ? body.startedAt : undefined, recordingDisclosureAt: typeof body.recordingDisclosureAt === "number" ? body.recordingDisclosureAt : undefined, recordingStatus: body.recordingStatus || "pending", } ) return NextResponse.json({ success: true, sessionId: result?._id, roomName: result?.roomName, callerPhone, contactProfile: contactContext?.contactProfile || null, recentLead: contactContext?.recentLead || null, recentSession: contactContext?.recentSession || null, }) } catch (error) { console.error("Failed to start phone call sync:", error) return NextResponse.json( { error: "Failed to start phone call sync" }, { status: 500 } ) } }