import { NextRequest, NextResponse } from 'next/server' import prisma from '@/lib/prisma' import { nanoid } from 'nanoid' import { getAuthUser } from '@/lib/auth' // GET /api/workflows - List workflows (public access for public workflows) export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url) const visibility = searchParams.get('visibility') || 'public' const limit = Math.min(parseInt(searchParams.get('limit') || '20'), 100) const offset = Math.max(parseInt(searchParams.get('offset') || '0'), 0) try { const authUser = await getAuthUser() const where: Record = {} // If authenticated, allow viewing own workflows (public + private) const creatorId = searchParams.get('creatorId') if (creatorId && authUser && creatorId === authUser.id) { where.creatorId = authUser.id } else if (visibility === 'public') { where.visibility = 'public' } else { where.visibility = 'public' } const workflows = await prisma.workflow.findMany({ where, orderBy: { createdAt: 'desc' }, take: limit, skip: offset, }) const total = await prisma.workflow.count({ where }) return NextResponse.json({ workflows, total, hasMore: offset + workflows.length < total }) } catch (error) { console.error('Error fetching workflows:', error) return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) } } // POST /api/workflows - Create workflow — requires authentication export async function POST(request: NextRequest) { try { const authUser = await getAuthUser() if (!authUser) { return NextResponse.json( { error: 'Authentication required' }, { status: 401 } ) } const body = await request.json() const { name, description, steps, variables, visibility } = body if (!name || !steps) { return NextResponse.json({ error: 'Name and steps are required' }, { status: 400 }) } // Generate unique slug const baseSlug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 50) const slug = `${baseSlug}-${nanoid(6)}` const workflow = await prisma.workflow.create({ data: { slug, name, description: description || null, steps, variables: variables || null, visibility: visibility || 'private', creatorId: authUser.id, } }) return NextResponse.json(workflow, { status: 201 }) } catch (error) { console.error('Error creating workflow:', error) return NextResponse.json({ error: 'Internal server error' }, { status: 500 }) } }