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