import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createKnowledgeBaseSchema } from '@server/validators/knowledge-base.validator';
import { listKbEntries, createKbEntry } from '@server/services/knowledge-base.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requireSection(req, 'knowledge_base');
    await requirePlanFeature(restaurantId!, 'knowledge_base');
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listKbEntries({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? undefined,
      type: p.get('type') ?? undefined,
      status: p.get('status') ?? undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
    });

    return NextResponse.json({ entries: result.data, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createKnowledgeBaseSchema, async (req) => {
      await requireSection(req, 'knowledge_base', 'create');
      await requirePlanFeature(req.session.restaurantId!, 'knowledge_base');
      const entry = await createKbEntry(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ entry }, { status: 201 });
    })
  )
);
