|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { photonImessageChatBackgroundContract } from '@/lib/api/contracts/tools/photon-imessage' |
| 5 | +import { parseRequest } from '@/lib/api/server' |
| 6 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 7 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 8 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 9 | +import { materializePhotonFile } from '@/app/api/tools/photon_imessage/route-helpers' |
| 10 | +import { setPhotonChatBackground } from '@/app/api/tools/photon_imessage/utils' |
| 11 | + |
| 12 | +export const dynamic = 'force-dynamic' |
| 13 | + |
| 14 | +const logger = createLogger('PhotonImessageChatBackgroundAPI') |
| 15 | + |
| 16 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 17 | + const requestId = generateRequestId() |
| 18 | + |
| 19 | + try { |
| 20 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 21 | + if (!authResult.success) { |
| 22 | + logger.warn( |
| 23 | + `[${requestId}] Unauthorized Photon chat background update attempt: ${authResult.error}` |
| 24 | + ) |
| 25 | + return NextResponse.json( |
| 26 | + { success: false, error: authResult.error || 'Authentication required' }, |
| 27 | + { status: 401 } |
| 28 | + ) |
| 29 | + } |
| 30 | + |
| 31 | + const parsed = await parseRequest(photonImessageChatBackgroundContract, request, {}) |
| 32 | + if (!parsed.success) return parsed.response |
| 33 | + const body = parsed.data.body |
| 34 | + |
| 35 | + if (body.clear) { |
| 36 | + const output = await setPhotonChatBackground({ |
| 37 | + projectId: body.projectId, |
| 38 | + projectSecret: body.projectSecret, |
| 39 | + to: body.to, |
| 40 | + clear: true, |
| 41 | + }) |
| 42 | + return NextResponse.json({ success: true, output }) |
| 43 | + } |
| 44 | + |
| 45 | + const file = await materializePhotonFile(body, { requestId, userId: authResult.userId }) |
| 46 | + if (file instanceof NextResponse) return file |
| 47 | + |
| 48 | + const output = await setPhotonChatBackground({ |
| 49 | + projectId: body.projectId, |
| 50 | + projectSecret: body.projectSecret, |
| 51 | + to: body.to, |
| 52 | + fileBuffer: file.buffer, |
| 53 | + fileName: file.fileName, |
| 54 | + mimeType: file.mimeType, |
| 55 | + }) |
| 56 | + return NextResponse.json({ success: true, output }) |
| 57 | + } catch (error) { |
| 58 | + const errorMessage = getErrorMessage(error, 'Unknown error occurred') |
| 59 | + logger.error(`[${requestId}] Photon chat background update failed:`, error) |
| 60 | + |
| 61 | + return NextResponse.json( |
| 62 | + { success: false, error: `Photon chat background update failed: ${errorMessage}` }, |
| 63 | + { status: 500 } |
| 64 | + ) |
| 65 | + } |
| 66 | +}) |
0 commit comments