/**
 * Sentry Tunnel API Route
 * =======================
 *
 * 解決問題: 前端 Sentry DSN 使用內網 IP (192.168.0.110:9000) 會觸發
 * 瀏覽器「存取區域網路上的其他裝置」權限對話框。
 *
 * 解決方案: 使用 Next.js API Route 作為 Tunnel，前端透過公網域名
 * (/api/sentry-tunnel) 發送事件，後端再轉發到內網 Sentry Server。
 *
 * 參考: https://docs.sentry.io/platforms/javascript/troubleshooting/#dealing-with-ad-blockers
 *
 * @see feedback_sentry_local_network.md
 * @see project_sentry_full_integration.md
 */

import { type NextRequest, NextResponse } from 'next/server';

// Sentry Self-Hosted 內網地址
// 2026-04-22 ogt: 改為讀 env var，避免內網 IP 硬碼進 bundle。
// K8s: awoooi-secrets → SENTRY_HOST；本機 dev fallback 維持原值不中斷。
const SENTRY_HOST = process.env.SENTRY_HOST ?? 'http://192.168.0.110:9000';

// 允許的 Project IDs (防止濫用)
const ALLOWED_PROJECT_IDS = new Set(['2', '3']); // awoooi-web: 2, awoooi-api: 3

export async function POST(request: NextRequest) {
  try {
    const envelope = await request.text();

    // 解析 envelope 取得 DSN 資訊
    const [header] = envelope.split('\n');
    const headerObj = JSON.parse(header);
    const dsn = headerObj.dsn;

    if (!dsn) {
      return NextResponse.json(
        { error: 'Missing DSN in envelope header' },
        { status: 400 }
      );
    }

    // 從 DSN 解析 Project ID
    // DSN 格式: http://<key>@<host>:<port>/<project_id>
    const projectId = dsn.split('/').pop();

    if (!projectId || !ALLOWED_PROJECT_IDS.has(projectId)) {
      return NextResponse.json(
        { error: 'Invalid or unauthorized project ID' },
        { status: 403 }
      );
    }

    // 轉發到 Sentry Server
    const response = await fetch(`${SENTRY_HOST}/api/${projectId}/envelope/`, {
      method: 'POST',
      body: envelope,
      headers: {
        'Content-Type': 'application/x-sentry-envelope',
      },
    });

    if (!response.ok) {
      console.error('[Sentry Tunnel] Forward failed:', response.status, response.statusText);
      return NextResponse.json(
        { error: 'Failed to forward to Sentry' },
        { status: response.status }
      );
    }

    return new NextResponse(null, { status: 200 });
  } catch (error) {
    console.error('[Sentry Tunnel] Error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

// 健康檢查端點
export async function GET() {
  return NextResponse.json({
    status: 'ok',
    tunnel: '/api/sentry-tunnel',
    target: SENTRY_HOST,
  });
}
