import * as Sentry from "@sentry/nextjs"

const SLOW_ACTION_THRESHOLD_MS = 1000

/**
 * Wraps a server action with performance timing instrumentation.
 * Measures execution duration, logs slow actions (>1s) as warnings,
 * and reports timing to Sentry as custom spans.
 */
export function withTiming<TArgs extends unknown[], TReturn>(
  actionName: string,
  fn: (...args: TArgs) => Promise<TReturn>,
): (...args: TArgs) => Promise<TReturn> {
  return async (...args: TArgs): Promise<TReturn> => {
    const start = performance.now()

    try {
      const result = await Sentry.startSpan(
        {
          name: actionName,
          op: "server.action",
          attributes: {
            "server_action.name": actionName,
          },
        },
        async (span) => {
          const res = await fn(...args)
          const durationMs = performance.now() - start

          span.setAttribute("server_action.duration_ms", durationMs)

          if (durationMs > SLOW_ACTION_THRESHOLD_MS) {
            console.warn(
              `[ServerAction] Slow action: ${actionName} took ${durationMs.toFixed(0)}ms`,
            )
            span.setAttribute("server_action.slow", true)
          }

          return res
        },
      )

      return result
    } catch (error) {
      const durationMs = performance.now() - start
      console.error(
        `[ServerAction] ${actionName} failed after ${durationMs.toFixed(0)}ms:`,
        error,
      )
      Sentry.captureException(error, {
        tags: { server_action: actionName },
        extra: { duration_ms: durationMs },
      })
      throw error
    }
  }
}
