import { NextRequest, NextResponse } from 'next/server'; import { z } from 'zod'; import { getSession } from '@/lib/auth'; import { getGHLClient } from '@/lib/api'; export async function GET(request: NextRequest) { const session = await getSession(); if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const ghl = await getGHLClient(session.user.id); if (!ghl) { return NextResponse.json( { error: 'GHL not configured for this user' }, { status: 400 } ); } const { searchParams } = new URL(request.url); const limit = parseInt(searchParams.get('limit') || '20'); const offset = parseInt(searchParams.get('offset') || '0'); const query = searchParams.get('query') || undefined; try { const contacts = await ghl.contacts.getAll({ limit, offset, query }); return NextResponse.json(contacts); } catch (error) { console.error('Failed to get contacts:', error); return NextResponse.json( { error: 'Failed to fetch contacts' }, { status: 500 } ); } } const createContactSchema = z.object({ firstName: z.string().optional(), lastName: z.string().optional(), email: z.string().email().optional(), phone: z.string().optional(), tags: z.array(z.string()).optional(), customFields: z.array(z.object({ key: z.string(), value: z.any(), })).optional(), }); export async function POST(request: NextRequest) { const session = await getSession(); if (!session) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const ghl = await getGHLClient(session.user.id); if (!ghl) { return NextResponse.json( { error: 'GHL not configured for this user' }, { status: 400 } ); } try { const body = await request.json(); const validated = createContactSchema.parse(body); const contact = await ghl.contacts.create(validated); return NextResponse.json(contact, { 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 contact:', error); return NextResponse.json( { error: 'Failed to create contact' }, { status: 500 } ); } }