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

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

export default defineEventHandler(async (event) => {
  try {
    // Get the case ID from the route parameter
    const caseId = getRouterParam(event, 'id');
    
    if (!caseId) {
      return {
        success: false,
        error: 'Case ID is required'
      };
    }

    // Check if the ID is a UUID or numeric ID
    const isUUID = caseId.length === 36 && caseId.includes('-');
    
    // Find the case instance by UUID or ID
    const caseInstance = await prisma.caseInstance.findFirst({
      where: isUUID 
        ? { caseUUID: caseId }
        : { caseID: parseInt(caseId) },
      include: {
        process: {
          select: {
            processID: true,
            processUUID: true,
            processName: true,
            processDescription: true
          }
        },
        startedBy: {
          select: {
            userID: true,
            userFullName: true,
            userUsername: true
          }
        },
        tasks: {
          include: {
            form: {
              select: {
                formID: true,
                formUUID: true,
                formName: true,
                formDescription: true,
                formComponents: true,
                formStatus: true,
                customCSS: true,
                customScript: true,
                formEvents: true,
                scriptMode: true
              }
            },
            assignedTo: {
              select: {
                userID: true,
                userFullName: true,
                userUsername: true
              }
            }
          }
        },
        timeline: {
          orderBy: {
            timelineDate: 'desc'
          },
          include: {
            createdBy: {
              select: {
                userID: true,
                userFullName: true,
                userUsername: true
              }
            }
          }
        }
      }
    });

    if (!caseInstance) {
      return {
        success: false,
        error: 'Case instance not found'
      };
    }

    // Extract forms from tasks and remove duplicates
    const forms = [];
    const formIds = new Set();
    
    for (const task of caseInstance.tasks) {
      if (task.form) {
        // Make sure formComponents is properly structured
        let formComponents = [];
        try {
          if (task.form.formComponents) {
            // Check if formComponents is already an array or needs to be extracted from a structure
            if (Array.isArray(task.form.formComponents)) {
              formComponents = task.form.formComponents;
            } else if (task.form.formComponents.components && Array.isArray(task.form.formComponents.components)) {
              formComponents = task.form.formComponents.components;
            } else {
              // Try to parse if it's a stringified JSON
              const parsedComponents = typeof task.form.formComponents === 'string' 
                ? JSON.parse(task.form.formComponents) 
                : task.form.formComponents;
              
              if (Array.isArray(parsedComponents)) {
                formComponents = parsedComponents;
              } else if (parsedComponents.components && Array.isArray(parsedComponents.components)) {
                formComponents = parsedComponents.components;
              }
            }
          }
        } catch (err) {
          console.error('Error parsing form components:', err);
        }
        
        // Extract form data from taskData if it exists
        let formData = null;
        if (task.taskData && task.taskData.formData) {
          formData = task.taskData.formData;
        }
        
        forms.push({
          ...task.form,
          formComponents: formComponents,
          taskId: task.taskID,
          taskUUID: task.taskUUID,
          taskStatus: task.taskStatus,
          taskName: task.taskName,
          taskData: task.taskData,
          formData: formData,
          submittedAt: task.taskData?.submittedAt || null,
          completedDate: task.taskCompletedDate
        });
      }
    }

    // Format the response
    const response = {
      caseInstance: {
        caseID: caseInstance.caseID,
        caseUUID: caseInstance.caseUUID,
        caseName: caseInstance.caseName,
        caseStatus: caseInstance.caseStatus,
        caseCreatedDate: caseInstance.caseCreatedDate,
        caseModifiedDate: caseInstance.caseModifiedDate,
        caseCompletedDate: caseInstance.caseCompletedDate,
        caseVariables: caseInstance.caseVariables,
        process: {
          processID: caseInstance.process.processID,
          processUUID: caseInstance.process.processUUID,
          processName: caseInstance.process.processName,
          processDescription: caseInstance.process.processDescription
        },
        startedBy: caseInstance.startedBy ? {
          userID: caseInstance.startedBy.userID,
          userFullName: caseInstance.startedBy.userFullName,
          userUsername: caseInstance.startedBy.userUsername
        } : null
      },
      forms: forms,
      timeline: caseInstance.timeline
    };

    return {
      success: true,
      ...response
    };
  } catch (error) {
    console.error('Error fetching case instance and forms:', error);
    
    return {
      success: false,
      error: 'Failed to fetch case instance and forms',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
}); 