import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
import { getTagsProvider } from '@/lib/ai/factory';
import { getSystemConfig } from '@/lib/config';
import { z } from 'zod';

const requestSchema = z.object({
  content: z.string().min(1, "Le contenu ne peut pas être vide"),
  notebookId: z.string().optional(),
  language: z.string().default('en'),
});

export async function POST(req: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { content, notebookId, language } = requestSchema.parse(body);

    // If notebookId is provided, use contextual suggestions (IA2)
    if (notebookId) {
      const suggestions = await contextualAutoTagService.suggestLabels(
        content,
        notebookId,
        session.user.id,
        language
      );

      // Convert label → tag to match TagSuggestion interface
      const convertedTags = suggestions.map(s => ({
        tag: s.label, // Convert label to tag
        confidence: s.confidence,
        // Keep additional properties for client-side use
        ...(s.reasoning && { reasoning: s.reasoning }),
        ...(s.isNewLabel !== undefined && { isNewLabel: s.isNewLabel })
      }));

      return NextResponse.json({ tags: convertedTags });
    }

    // Otherwise, use legacy auto-tagging (generates new tags)
    const config = await getSystemConfig();
    const provider = getTagsProvider(config);
    const tags = await provider.generateTags(content, language);

    return NextResponse.json({ tags });
  } catch (error: any) {

    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: error.issues }, { status: 400 });
    }

    return NextResponse.json(
      { error: error.message || 'Erreur lors de la génération des tags' },
      { status: 500 }
    );
  }
}
