import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { synthesizeSpeech } from '@server/services/voice/tts.service';

const PREVIEW_TEXT = 'Hello! How can I help you today?';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const body = await req.json() as { voiceModelId?: string; text?: string; languageCode?: string };
    const { voiceModelId, text, languageCode } = body;

    const previewText = (text?.trim() || PREVIEW_TEXT).slice(0, 200);
    const restaurantId = req.session.restaurantId ?? null;

    try {
      const result = await synthesizeSpeech(previewText, voiceModelId || null, restaurantId, languageCode || null);
      const ab = result.audioBuffer.buffer.slice(
        result.audioBuffer.byteOffset,
        result.audioBuffer.byteOffset + result.audioBuffer.byteLength
      ) as ArrayBuffer;
      return new NextResponse(ab, {
        status: 200,
        headers: {
          'Content-Type': result.contentType,
          'Content-Length': String(result.audioBuffer.length),
          'Cache-Control': 'no-store',
        },
      });
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      console.warn('[VoicePreview] TTS failed:', msg);
      return NextResponse.json({ error: msg }, { status: 422 });
    }
  })
);
