import { NextRequest } from 'next/server';
import { OLLAMA_URL } from '../../../lib/ollama-config';

const FALLBACK_TITLE = 'New Conversation';

function cleanTitle(raw: string): string {
  const title = raw
    .replace(/["'`]/g, '')
    .replace(/[\n\r]/g, ' ')
    .trim();
  if (!title) return FALLBACK_TITLE;
  return title.split(/\s+/).slice(0, 6).join(' ');
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const message = String(body?.message || '').trim();
    const model = String(body?.model || '').trim();

    if (!message || !model) {
      return new Response(JSON.stringify({ title: FALLBACK_TITLE }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 5000);

    const prompt =
      'Generate a 3-5 word title for a conversation that starts with this message. Reply with ONLY the title and no punctuation.\n\n' +
      message;

    const response = await fetch(`${OLLAMA_URL}/api/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ model, prompt, stream: false }),
      signal: controller.signal,
    });

    clearTimeout(timeout);

    if (!response.ok) {
      return new Response(JSON.stringify({ title: FALLBACK_TITLE }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    const data = (await response.json()) as { response?: string };
    const title = cleanTitle(data.response || '');

    return new Response(JSON.stringify({ title }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch {
    return new Response(JSON.stringify({ title: FALLBACK_TITLE }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}
