import { NextRequest, NextResponse } from 'next/server' import { prisma } from '@/lib/db/prisma' import { getCurrentUser } from '@/lib/auth' import { canAccessWorkspace } from '@/lib/db/workspace-access' // GET /api/workspaces/[id]/care-tasks export async function GET( request: NextRequest, { params }: { params: { id: string } } ) { try { const user = await getCurrentUser() if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const workspaceId = params.id const access = await canAccessWorkspace(user.id, workspaceId) if (!access) { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) } const tasks = await prisma.careTask.findMany({ where: { workspaceId }, orderBy: [ { completedAt: 'asc' }, { priority: 'desc' }, { createdAt: 'desc' } ], include: { assignedTo: { select: { id: true, name: true } }, completedBy: { select: { id: true, name: true } }, createdBy: { select: { id: true, name: true } } } }) return NextResponse.json({ tasks }) } catch (error) { console.error('Failed to fetch care tasks:', error) return NextResponse.json( { error: 'Failed to fetch care tasks' }, { status: 500 } ) } } // POST /api/workspaces/[id]/care-tasks export async function POST( request: NextRequest, { params }: { params: { id: string } } ) { try { const user = await getCurrentUser() if (!user) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } const workspaceId = params.id const access = await canAccessWorkspace(user.id, workspaceId) if (!access || access.role === 'VIEWER') { return NextResponse.json({ error: 'Forbidden' }, { status: 403 }) } const body = await request.json() const { title, description, priority, category, dueAt, assignedToId } = body const task = await prisma.careTask.create({ data: { workspaceId, title, description, priority: priority || 'MEDIUM', category: category || 'GENERAL', dueAt: dueAt ? new Date(dueAt) : null, assignedToId: assignedToId || null, createdById: user.id, }, include: { assignedTo: { select: { id: true, name: true } }, createdBy: { select: { id: true, name: true } } } }) // Log audit await prisma.auditLog.create({ data: { workspaceId, userId: user.id, action: 'CREATE', entityType: 'CARE_TASK', entityId: task.id, details: { title, priority, category } } }) return NextResponse.json({ task }) } catch (error) { console.error('Failed to create care task:', error) return NextResponse.json( { error: 'Failed to create care task' }, { status: 500 } ) } }