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

export default defineEventHandler(async (event) => {
  try {
    // Get organization ID from route
    const orgId = parseInt(event.context.params.id);
    
    if (isNaN(orgId)) {
      return {
        statusCode: 400,
        message: "Invalid organization ID"
      };
    }
    
    // Check if organization exists
    const organization = await prisma.organization.findUnique({
      where: {
        org_id: orgId
      }
    });
    
    if (!organization) {
      return {
        statusCode: 404,
        message: "Organization not found"
      };
    }
    
    // Get departments for this organization
    const departments = await prisma.department.findMany({
      where: {
        org_id: orgId
      },
      orderBy: {
        dp_name: 'asc'
      },
      include: {
        _count: {
          select: {
            cabinets: true,
            users: true
          }
        }
      }
    });
    
    return {
      statusCode: 200,
      data: departments,
      meta: {
        organization: {
          org_id: organization.org_id,
          org_name: organization.org_name
        },
        total: departments.length
      }
    };
  } catch (error) {
    console.error("Error fetching departments by organization:", error);
    
    return {
      statusCode: 500,
      message: "Internal server error",
      error: error.message
    };
  }
}); 