'use server'

import {headers} from 'next/headers'

export async function getClientIp(): Promise<{ip?: string, error?: string}> {
  const header = await headers()
  try {
    const forwardedFor = header.get('x-forwarded-for')
    if (forwardedFor) {
      const ip = forwardedFor.split(',')[0].trim()
      if (ip) return {ip}
    }
    const realIp = header.get('x-real-ip')
    if (realIp) return {ip: realIp}
    return {error: '无法获取IP'}
  }
  catch (error) {
    return {error: error instanceof Error ? error.message : '获取失败'}
  }
}
