import { useToString } from '@vueuse/core'
export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const keywords = useToString(query.search).value.split(' ')

  function pipelineFilter(keywords) {
    var result = [{}]
    keywords.forEach((keyword, index) => {
      result[index] = {
        $match: {
          $or: [
            {
              'regencies.districts.villages.name': {
                $regex: (index === 0 ? '^' : '') + keyword,
                $options: 'i',
              },
            },
            {
              'regencies.districts.name': {
                $regex: (index === 0 ? '^' : '') + keyword,
                $options: 'i',
              },
            },
            {
              'regencies.name': {
                $regex: (index === 0 ? '^(KOTA|KABUPATEN) ' : '') + keyword,
                $options: 'i',
              },
            },
            {
              name: {
                $regex: (index === 0 ? '^' : '') + keyword,
                $options: 'i',
              },
            },
          ],
        },
      }
    })
    return result
  }

  try {
    const results = await prisma.address.aggregateRaw({
      pipeline: [
        { $unwind: { path: '$regencies' } },
        { $unwind: { path: '$regencies.districts' } },
        {
          $unwind: {
            path: '$regencies.districts.villages',
          },
        },

        ...pipelineFilter(keywords),
        {
          $limit: 10,
        },
        {
          $project: {
            _id: 1,
            name: 1,
            regencies: {
              _id: 1,
              name: 1,
              districts: {
                _id: 1,
                name: 1,
                villages: {
                  _id: 1,
                  name: 1,
                },
              },
            },
          },
        },
      ],
    })
    return results.map((result) => {
      return {
        _id: 'ID',
        name: 'INDONESIA',
        states: result,
        display: `DESA/KEL ${result.regencies.districts.villages.name} KEC. ${result.regencies.districts.name} ${result.regencies.name} PROVINSI ${result.name}`,
      }
    })
  } catch (error) {
    // Return error if fetching users fails
    return {
      status: 500,
      body: { message: 'Failed to fetch address' },
    }
  }
})
