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

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

export default defineEventHandler(async (event) => {
  try {
    // Get query parameters
    const query = getQuery(event);
    const caseId = query.caseId;
    const status = query.status;
    const assignedTo = query.assignedTo;
    const page = parseInt(query.page) || 1;
    const limit = parseInt(query.limit) || 10;
    const skip = (page - 1) * limit;
    
    // Build where clause
    const where = {};
    
    if (caseId) {
      where.caseID = parseInt(caseId);
    }
    
    if (status) {
      where.taskStatus = status;
    }
    
    if (assignedTo) {
      where.taskAssignedTo = parseInt(assignedTo);
    }
    
    // Fetch tasks
    const tasks = await prisma.task.findMany({
      where,
      include: {
        case: {
          select: {
            caseID: true,
            caseUUID: true,
            caseName: true,
            caseStatus: true,
            process: {
              select: {
                processID: true,
                processUUID: true,
                processName: true
              }
            }
          }
        },
        assignedTo: {
          select: {
            userID: true,
            userFullName: true,
            userUsername: true
          }
        },
        form: {
          select: {
            formID: true,
            formUUID: true,
            formName: true,
            formDescription: true
          }
        }
      },
      orderBy: {
        taskCreatedDate: 'desc'
      },
      skip,
      take: limit
    });
    
    // Count total tasks for pagination
    const totalTasks = await prisma.task.count({ where });
    
    return {
      success: true,
      tasks,
      pagination: {
        page,
        limit,
        totalItems: totalTasks,
        totalPages: Math.ceil(totalTasks / limit)
      }
    };
  } catch (error) {
    console.error('Error fetching tasks:', error);
    
    return {
      success: false,
      error: 'Failed to fetch tasks',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
}); 