import { NextRequest, NextResponse } from 'next/server';
import { getIdeaMotriz, saveIdeaMotriz } from '@/lib/file-service';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params;
    const ideaMotriz = await getIdeaMotriz(slug);
    return NextResponse.json(ideaMotriz);
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params;
    const { action, input, current } = await request.json();

    let ideaMotriz;
    if (action === 'generate') {
      const { generateIdeaMotriz } = await import('@/lib/llm-service');
      ideaMotriz = await generateIdeaMotriz(input);
    } else if (action === 'refine' && current) {
      const { refineIdeaMotriz } = await import('@/lib/llm-service');
      ideaMotriz = await refineIdeaMotriz(current, input);
    } else if (action === 'save') {
      await saveIdeaMotriz(slug, input);
      return NextResponse.json({ success: true });
    } else {
      return NextResponse.json({ error: 'Acción inválida' }, { status: 400 });
    }

    await saveIdeaMotriz(slug, ideaMotriz);
    return NextResponse.json(ideaMotriz);
  } catch (error: any) {
    console.error('Error en idea-motriz:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
