/// <reference path="../pb_data/types.d.ts" />

onRecordAfterCreateSuccess((e) => {
  const record = e.record
  const userId = record.getString('userId')

  if (!userId) return e.next()

  const tokenRecords = $app.findRecordsByFilter(
    'fcm_tokens',
    `userId = "${userId}"`,
    '-created',
    500,
    0
  )

  if (!tokenRecords || tokenRecords.length === 0) return e.next()

  const tokens = tokenRecords
    .map(r => r.getString('token'))
    .filter(t => t.length > 0)

  if (tokens.length === 0) return e.next()

  const sidecarUrl = $os.getenv('SIDECAR_URL') || 'http://localhost:8091'
  const sidecarSecret = $os.getenv('SIDECAR_SECRET') || ''

  try {
    const res = $http.send({
      url: sidecarUrl + '/notify',
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-sidecar-secret': sidecarSecret
      },
      body: JSON.stringify({
        tokens: tokens,
        title: record.getString('title'),
        body: record.getString('body')
      }),
      timeout: 10
    })

    if (res.statusCode !== 200) {
      e.app.logger().error('FCM relay failed',
        'status', res.statusCode,
        'response', JSON.stringify(res.json)
      )
    }
  } catch (err) {
    e.app.logger().error('FCM relay error', 'error', err)
  }

  return e.next()
}, 'notifications')
