export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { getRuntimeEnv } from '@/lib/ipconfig'
import fs from 'fs'

// ✅ 重定向 console.log / console.error 到文件
const logStream = fs.createWriteStream('/tmp/health-api.log', { flags: 'a' });

console.log = (...args: any[]) => {
  logStream.write(`[log ${new Date().toISOString()}] ${args.join(' ')}\n`);
};

console.error = (...args: any[]) => {
  logStream.write(`[error ${new Date().toISOString()}] ${args.join(' ')}\n`);
};

export async function GET() {
  let ip: string | null = null
  let res: string | undefined = undefined

  try {
    console.log('✅ [health-check] API HIT');
    res = await getRuntimeEnv('SUPABASE_URL')
    ip = res ?? null

    console.log('[health-check] getRuntimeEnv("SUPABASE_URL") 返回：', res)
    console.log('[health-check] ip 赋值结果：', ip)
  } catch (e: any) {
    ip = null
    console.error('[health-check] 捕获异常：', e)
  }

  console.log('[health-check] process.env.SUPABASE_URL =', process.env.SUPABASE_URL)

  return NextResponse.json({
    status: 'ok',
    ip,
  })
}
