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

export default defineEventHandler(async (event) => {
  try {
    // Get query parameters
    const query = getQuery(event);
    const page = parseInt(query.page) || 1;
    const limit = parseInt(query.limit) || 10;
    const search = query.search || '';
    const departmentId = query.dp_id ? parseInt(query.dp_id) : null;
    const status = query.status || null;
    
    // Calculate pagination
    const skip = (page - 1) * limit;
    
    // Define filters
    const filters = {
      where: {}
    };
    
    // Filter by department if provided
    if (departmentId) {
      filters.where.dp_id = departmentId;
    }
    
    // Filter by status if provided
    if (status) {
      filters.where.userStatus = status;
    }
    
    // Add search filter if provided
    if (search) {
      filters.where = {
        ...filters.where,
        OR: [
          { userUsername: { contains: search } },
          { userFullName: { contains: search } },
          { userEmail: { contains: search } }
        ]
      };
    }
    
    // Get users with pagination
    const [users, total] = await Promise.all([
      prisma.user.findMany({
        ...filters,
        skip,
        take: limit,
        orderBy: {
          userFullName: 'asc'
        },
        select: {
          userID: true,
          userUsername: true,
          userFullName: true,
          userEmail: true,
          userPhone: true,
          userStatus: true,
          dp_id: true,
          userCreatedDate: true,
          userModifiedDate: true,
          department: {
            select: {
              dp_id: true,
              dp_name: true,
              organization: {
                select: {
                  org_id: true,
                  org_name: true
                }
              }
            }
          },
          userrole: {
            select: {
              userRoleID: true,
              role: {
                select: {
                  roleID: true,
                  roleName: true
                }
              }
            }
          }
        }
      }),
      prisma.user.count(filters)
    ]);
    
    // Calculate pagination metadata
    const totalPages = Math.ceil(total / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;
    
    return {
      statusCode: 200,
      data: users,
      meta: {
        page,
        limit,
        total,
        totalPages,
        hasNextPage,
        hasPrevPage
      }
    };
  } catch (error) {
    console.error("Error fetching users:", error);
    
    return {
      statusCode: 500,
      message: "Internal server error",
      error: error.message
    };
  }
}); 