import { NextRequest, NextResponse } from 'next/server'; import { z } from 'zod'; import { getSession } from '@/lib/auth'; import { getGHLClientForUser } from '@/lib/ghl/helpers'; export async function GET(request: NextRequest) { const session = await getSession(); if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const ghl = await getGHLClientForUser(session.user.id); if (!ghl) { return NextResponse.json({ error: 'GHL not configured' }, { status: 400 }); } const { searchParams } = new URL(request.url); const pipelineId = searchParams.get('pipelineId') || undefined; const pipelineStageId = searchParams.get('stageId') || undefined; const status = searchParams.get('status') as 'open' | 'won' | 'lost' | 'abandoned' | 'all' || undefined; const limit = parseInt(searchParams.get('limit') || '50'); try { const opportunities = await ghl.opportunities.getAll({ pipelineId, pipelineStageId, status, limit, }); return NextResponse.json(opportunities); } catch (error) { console.error('Failed to get opportunities:', error); return NextResponse.json({ error: 'Failed to fetch opportunities' }, { status: 500 }); } } const createOpportunitySchema = z.object({ name: z.string().min(1), pipelineId: z.string(), pipelineStageId: z.string(), contactId: z.string(), monetaryValue: z.number().optional(), status: z.enum(['open', 'won', 'lost', 'abandoned']).optional(), }); export async function POST(request: NextRequest) { const session = await getSession(); if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const ghl = await getGHLClientForUser(session.user.id); if (!ghl) { return NextResponse.json({ error: 'GHL not configured' }, { status: 400 }); } try { const body = await request.json(); const validated = createOpportunitySchema.parse(body); const opportunity = await ghl.opportunities.create(validated); return NextResponse.json(opportunity, { status: 201 }); } catch (error) { if (error instanceof z.ZodError) { return NextResponse.json({ error: 'Validation failed', details: error.issues }, { status: 400 }); } console.error('Failed to create opportunity:', error); return NextResponse.json({ error: 'Failed to create opportunity' }, { status: 500 }); } }