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

import { childLogger } from '@server/logger';
const log = childLogger('route.ai_agents.voice_preview');

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

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const restaurantId = req.session.restaurantId ?? null;
    await requireSection(req, 'ai_config');
    if (restaurantId) {
      await requirePlanFeature(restaurantId, 'voice_agent');
    }

    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);

    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);
      log.warn({ msg }, 'VoicePreview TTS failed');
      return NextResponse.json({ error: msg }, { status: 422 });
    }
  })
);
