import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { reEmbedAll } from '@server/services/kb-embeddings.service';
import { initDatabase } from '@server/db/init';
import { requirePlanFeature } from '@server/utils/features';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId } = req.session;
    if (!restaurantId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    await requireSection(req, 'knowledge_base', 'update');
    await requirePlanFeature(restaurantId, 'knowledge_base');
    await initDatabase();
    const result = await reEmbedAll(restaurantId);
    return NextResponse.json({ success: true, queued: result.queued });
  })
);
