import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { findDuplicates } from '@/lib/services/clients.service';
import { errorResponse } from '@/lib/errors';

const duplicateQuerySchema = z.object({
  name: z.string().min(1),
});

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx) => {
    try {
      const { name } = parseQuery(req, duplicateQuerySchema);
      const data = await findDuplicates(ctx.portId, name);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
