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 || '';
    
    // Calculate pagination
    const skip = (page - 1) * limit;
    
    // Define filters
    const filters = {
      where: {}
    };
    
    // Add search filter if provided
    if (search) {
      filters.where = {
        OR: [
          { org_name: { contains: search } },
          { org_address1: { contains: search } },
          { org_state: { contains: search } },
          { org_country: { contains: search } }
        ]
      };
    }
    
    // Get organizations with pagination
    const [organizations, total] = await Promise.all([
      prisma.organization.findMany({
        ...filters,
        skip,
        take: limit,
        orderBy: {
          org_name: 'asc'
        },
        include: {
          _count: {
            select: {
              departments: true
            }
          }
        }
      }),
      prisma.organization.count(filters)
    ]);
    
    // Calculate pagination metadata
    const totalPages = Math.ceil(total / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;
    
    return {
      statusCode: 200,
      data: organizations,
      meta: {
        page,
        limit,
        total,
        totalPages,
        hasNextPage,
        hasPrevPage
      }
    };
  } catch (error) {
    console.error("Error fetching organizations:", error);
    
    return {
      statusCode: 500,
      message: "Internal server error",
      error: error.message
    };
  }
}); 