import { useToString } from '@vueuse/core'

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const parent = JSON.parse(query.parent)

  try {
    const results = await prisma.address.aggregateRaw({
      pipeline: [
        { $unwind: { path: '$regencies' } },
        { $unwind: { path: '$regencies.districts' } },
        {
          $match: {
            'regencies._id': parent._id,
          },
        },
        {
          $project: {
            _id: '$regencies.districts._id',
            name: '$regencies.districts.name',
          },
        },
      ],
    })
    return results
  } catch (error) {
    // Return error if fetching users fails
    return {
      status: 500,
      body: { message: 'Failed to fetch districts' },
    }
  }
})
