import { PrismaClient } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';

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

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

    console.log('Starting process with ID:', processId);

    // Check if the ID is a UUID or numeric ID
    const isUUID = processId.length === 36 && processId.includes('-');
    
    // Find the process
    console.log('Finding process...');
    const process = await prisma.process.findFirst({
      where: isUUID 
        ? { processUUID: processId }
        : { processID: parseInt(processId) },
      include: {
        creator: {
          select: {
            userID: true,
            userFullName: true,
            userUsername: true
          }
        }
      }
    });

    if (!process) {
      console.log('Process not found');
      return {
        success: false,
        error: 'Process not found'
      };
    }

    console.log('Process found:', process.processName);

    // Check if process is published
    if (process.processStatus !== 'published') {
      console.log('Process is not published:', process.processStatus);
      return {
        success: false,
        error: 'Cannot start an unpublished process'
      };
    }

    // Get the current user (in a real app, this would come from the authenticated user)
    const currentUser = {
      userID: 1, // This would be the actual user ID in a real app
      userFullName: 'John Doe',
      userUsername: 'johndoe'
    };

    console.log('Creating case instance...');
    // Create a new case instance
    const caseInstance = await prisma.caseInstance.create({
      data: {
        caseUUID: uuidv4(),
        processID: process.processID,
        caseName: `${process.processName} - ${new Date().toLocaleDateString()}`,
        caseStatus: 'active',
        caseStartedBy: currentUser.userID,
        caseVariables: process.processVariables || {},
        caseSettings: process.processSettings || {},
        caseDefinition: process.processDefinition || {},
        caseCreatedDate: new Date(),
        caseModifiedDate: new Date()
      }
    });

    console.log('Case instance created:', caseInstance.caseUUID);

    console.log('Process started successfully - tasks will be created dynamically during workflow execution');

    // Add to case timeline
    console.log('Adding to case timeline...');
    await prisma.caseTimeline.create({
      data: {
        caseID: caseInstance.caseID,
        timelineType: 'start',
        timelineDescription: `Process started by ${currentUser.userFullName}`,
        timelineDate: new Date(),
        timelineCreatedBy: currentUser.userID
      }
    });

    console.log('Process started successfully');
    return {
      success: true,
      data: {
        case: {
          id: caseInstance.caseUUID,
          name: caseInstance.caseName,
          status: caseInstance.caseStatus,
          startedAt: caseInstance.caseCreatedDate
        }
      }
    };
  } catch (error) {
    console.error('Error starting process:', error);
    console.error('Error details:', {
      name: error.name,
      message: error.message,
      stack: error.stack,
      code: error.code
    });
    
    return {
      success: false,
      error: 'Failed to start process',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  } finally {
    // Close the Prisma client connection
    await prisma.$disconnect();
  }
}); 