import { PrismaClient } from '@prisma/client';

// Initialize Prisma client
const prisma = new PrismaClient();

export default defineEventHandler(async (event) => {
  // Get the task ID from the route params
  const taskId = event.context.params.id;
  
  try {
    // Parse the request body
    const body = await readBody(event);
    
    // Validate required fields
    if (!body.formData) {
      return {
        success: false,
        error: 'Form data is required'
      };
    }
    
    // Find the task
    let task;
    
    if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(taskId)) {
      // If it looks like a UUID
      task = await prisma.task.findUnique({
        where: { taskUUID: taskId }
      });
    } else if (!isNaN(parseInt(taskId))) {
      // If it's a numeric ID
      task = await prisma.task.findUnique({
        where: { taskID: parseInt(taskId) }
      });
    }
    
    if (!task) {
      return {
        success: false,
        error: 'Task not found'
      };
    }
    
    // Update the task with the draft form data
    const updatedTask = await prisma.task.update({
      where: {
        taskID: task.taskID
      },
      data: {
        taskData: {
          ...task.taskData,
          formData: body.formData,
          lastSaved: new Date().toISOString(),
          isDraft: true
        }
      }
    });
    
    return {
      success: true,
      task: updatedTask
    };
  } catch (error) {
    console.error(`Error saving draft for task ${taskId}:`, error);
    
    return {
      success: false,
      error: 'Failed to save draft',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
}); 