import { NextRequest, NextResponse } from 'next/server'; import { authenticateIntegrationRequest } from '@/lib/integrations-auth'; import { createClient } from '@supabase/supabase-js'; export async function POST(req: NextRequest) { let body: any; try { body = await req.json(); } catch { return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 }); } const auth = await authenticateIntegrationRequest(req, { requireTenant: true, parsedBody: body }); if (!auth.ok) { return auth.errorResponse!; } const tenantId = auth.tenantId!; const eventType = body.event_type || 'notice'; const actor = auth.caller || body.actor || 'system'; const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!; const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY!; const adminClient = createClient(supabaseUrl, serviceRoleKey); const { data: event, error } = await adminClient .from('creative_events') .insert({ tenant_id: tenantId, creative_id: body.creative_id || null, event_type: eventType, actor, from_status: body.from_status || null, to_status: body.to_status || null, payload: body.payload || {}, visibility: body.visibility || 'agency', }) .select('*') .single(); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ ok: true, event, }); }