import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, 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';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    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) => {
      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) => {
    const { id } = await ctx.params;
    await deleteKbEntry(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
