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 },
        include: {
          case: true
        }
      });
    } else if (!isNaN(parseInt(taskId))) {
      // If it's a numeric ID
      task = await prisma.task.findUnique({
        where: { taskID: parseInt(taskId) },
        include: {
          case: true
        }
      });
    }
    
    if (!task) {
      return {
        success: false,
        error: 'Task not found'
      };
    }
    
    // Update the task with the submitted form data
    const updatedTask = await prisma.task.update({
      where: {
        taskID: task.taskID
      },
      data: {
        taskStatus: 'completed',
        taskCompletedDate: new Date(),
        taskData: {
          ...task.taskData,
          formData: body.formData,
          submittedAt: new Date().toISOString()
        }
      }
    });
    
    // Add an entry to the case timeline
    await prisma.caseTimeline.create({
      data: {
        caseID: task.caseID,
        timelineType: 'task_completed',
        timelineDescription: `Task "${task.taskName}" was completed`,
        timelineCreatedBy: task.taskAssignedTo
      }
    });
    
    // Check if all tasks for the case are completed
    const remainingTasks = await prisma.task.count({
      where: {
        caseID: task.caseID,
        taskStatus: {
          not: 'completed'
        }
      }
    });
    
    // If all tasks are completed, update the case status
    if (remainingTasks === 0) {
      await prisma.caseInstance.update({
        where: {
          caseID: task.caseID
        },
        data: {
          caseStatus: 'completed',
          caseCompletedDate: new Date()
        }
      });
      
      // Add an entry to the case timeline
      await prisma.caseTimeline.create({
        data: {
          caseID: task.caseID,
          timelineType: 'case_completed',
          timelineDescription: `Case "${task.case.caseName}" was completed`,
          timelineCreatedBy: task.taskAssignedTo
        }
      });
    }
    
    return {
      success: true,
      task: updatedTask
    };
  } catch (error) {
    console.error(`Error submitting form for task ${taskId}:`, error);
    
    return {
      success: false,
      error: 'Failed to submit form',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
}); 