function sentryEndpoint(dsn: string) {
  try {
    const url = new URL(dsn)
    const projectId = url.pathname.replace(/^\/+/, '').split('/').pop()
    const publicKey = url.username
    if (!projectId || !publicKey) return null
    return {
      url: `${url.protocol}//${url.host}/api/${projectId}/store/`,
      publicKey,
    }
  } catch {
    return null
  }
}

export async function captureWebException(error: Error, context: Record<string, unknown> = {}) {
  const dsn = process.env.NEXT_PUBLIC_SENTRY_DSN || ''
  const endpoint = dsn ? sentryEndpoint(dsn) : null
  if (!endpoint) return

  const eventId = String(context.incidentId || crypto.randomUUID()).replaceAll('-', '').slice(0, 32)
  try {
    await fetch(endpoint.url, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'x-sentry-auth': `Sentry sentry_version=7, sentry_key=${endpoint.publicKey}, sentry_client=dlbdi-web-lite/0.1`,
      },
      body: JSON.stringify({
        event_id: eventId,
        platform: 'javascript',
        logger: 'dlbdi-web',
        level: 'error',
        environment: process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENT || process.env.NODE_ENV || 'development',
        message: error.message,
        exception: {
          values: [{
            type: error.name || 'Error',
            value: error.message,
          }],
        },
        extra: context,
        timestamp: new Date().toISOString(),
      }),
    })
  } catch {
    // Error pages must never fail because telemetry is unavailable.
  }
}
