import prisma from "../../../utils/prisma";

export default defineEventHandler(async (event) => {
  try {
    // Get department ID from route
    const departmentId = parseInt(event.context.params.id);
    
    if (isNaN(departmentId)) {
      return {
        statusCode: 400,
        message: "Invalid department ID"
      };
    }
    
    // Check if department exists
    const department = await prisma.department.findUnique({
      where: {
        dp_id: departmentId
      }
    });
    
    if (!department) {
      return {
        statusCode: 404,
        message: "Department not found"
      };
    }
    
    // Get users for this department
    const users = await prisma.user.findMany({
      where: {
        dp_id: departmentId
      },
      orderBy: {
        userFullName: 'asc'
      },
      select: {
        userID: true,
        userUsername: true,
        userFullName: true,
        userEmail: true,
        userPhone: true,
        userStatus: true,
        userCreatedDate: true,
        userModifiedDate: true,
        userrole: {
          select: {
            userRoleID: true,
            role: {
              select: {
                roleID: true,
                roleName: true
              }
            }
          }
        }
      }
    });
    
    return {
      statusCode: 200,
      data: users,
      meta: {
        department: {
          dp_id: department.dp_id,
          dp_name: department.dp_name
        },
        total: users.length
      }
    };
  } catch (error) {
    console.error("Error fetching users by department:", error);
    
    return {
      statusCode: 500,
      message: "Internal server error",
      error: error.message
    };
  }
}); 