/**
 * Timeline proxy route — forwards timeline queries to platform-service.
 */

import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import { logError } from '@/lib/logger';

const PLATFORM_URL = process.env.PLATFORM_SERVICE_URL || 'http://localhost:4003';

export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const url = new URL(req.url);
    const productOverride = url.searchParams.get('productId')?.trim();
    if (productOverride) {
      url.searchParams.delete('productId');
    }
    const qs = url.search;
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'x-request-id': req.headers.get('x-request-id') || crypto.randomUUID(),
      'x-user-id': caller.id,
      'x-product-id':
        productOverride || req.headers.get('x-product-id') || process.env.PRODUCT_ID || 'lysnrai',
    };

    const res = await fetch(`${PLATFORM_URL}/api/timeline${qs}`, {
      method: 'GET',
      headers,
    });

    const data = await res.json().catch(() => null);
    return NextResponse.json(data ?? { error: res.statusText }, { status: res.status });
  } catch (error) {
    logError('Timeline proxy error', error);
    return NextResponse.json({ error: 'Service unavailable' }, { status: 502 });
  }
}
