import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updateKnowledgeBaseSchema } from '@server/validators/knowledge-base.validator';
import { getKbEntry, updateKbEntry, deleteKbEntry } from '@server/services/knowledge-base.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'knowledge_base');
    await requirePlanFeature(req.session.restaurantId!, 'knowledge_base');
    const { id } = await ctx.params;
    const entry = await getKbEntry(id, req.session.restaurantId!);
    return NextResponse.json({ entry });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateKnowledgeBaseSchema, async (req, ctx: RouteContext) => {
      await requireSection(req, 'knowledge_base', 'update');
      await requirePlanFeature(req.session.restaurantId!, 'knowledge_base');
      const { id } = await ctx.params;
      const entry = await updateKbEntry(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ entry });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'knowledge_base', 'delete');
    await requirePlanFeature(req.session.restaurantId!, 'knowledge_base');
    const { id } = await ctx.params;
    await deleteKbEntry(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
