import { auth } from '@clerk/nextjs/server';

export const runtime = 'edge';

export async function POST(request: Request) {
  try {
    // Check authentication
    const { userId } = await auth();

    if (!userId) {
      return new Response(
        JSON.stringify({ error: 'Unauthorized - Please sign in' }),
        {
          status: 401,
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );
    }

    const body = await request.json();
    const { text } = body;

    // Make the upstream request
    const response = await fetch('https://api.openai.com/v1/audio/speech', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        model: 'tts-1',
        input: text,
        voice: 'ash',
        response_format: 'mp3',
      }),
    });

    // Return the streaming response directly
    return new Response(response.body, {
      status: response.status,
      headers: {
        'Content-Type': response.headers.get('Content-Type'),
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
        // Forward other important headers
        ...Object.fromEntries(
          ['Content-Encoding', 'Transfer-Encoding']
            .map((h) => [h, response.headers.get(h)])
            .filter(([_, v]) => v)
        ),
      },
    });
  } catch (error: any) {
    return new Response(
      JSON.stringify({ error: 'Proxy error', message: error.message }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    );
  }
}
