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 { buildPhoneCallSummary, sendPhoneCallSummaryEmail, } from "@/lib/phone-calls" export async function POST(request: Request) { const authError = await requirePhoneAgentInternalAuth(request) if (authError) { return authError } try { const body = await request.json() const callId = String(body.sessionId || body.roomName || "") if (!callId) { return NextResponse.json( { error: "sessionId or roomName is required" }, { status: 400 } ) } const detail = await fetchQuery(api.voiceSessions.getAdminPhoneCallDetail, { callId, }) if (!detail) { return NextResponse.json( { error: "Phone call not found" }, { status: 404 } ) } const url = new URL(request.url) const summaryText = buildPhoneCallSummary(detail) const notificationResult = await sendPhoneCallSummaryEmail({ detail: { ...detail, call: { ...detail.call, summaryText, }, }, adminUrl: url.origin, }) const result = await fetchMutation(api.voiceSessions.completeSession, { sessionId: detail.call.id, endedAt: typeof body.endedAt === "number" ? body.endedAt : Date.now(), callStatus: body.callStatus || (body.error ? "failed" : "completed"), recordingStatus: body.recordingStatus, recordingId: body.recordingId ? String(body.recordingId) : undefined, recordingUrl: body.recordingUrl ? String(body.recordingUrl) : undefined, recordingError: body.recordingError ? String(body.recordingError) : undefined, summaryText, notificationStatus: notificationResult.status, notificationSentAt: notificationResult.status === "sent" ? Date.now() : undefined, notificationError: notificationResult.error, }) return NextResponse.json({ success: true, call: result, notification: notificationResult, }) } catch (error) { console.error("Failed to complete phone call sync:", error) return NextResponse.json( { error: "Failed to complete phone call sync" }, { status: 500 } ) } }