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

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

const setTagsSchema = z.object({
  tagIds: z.array(z.string()),
});

export const PUT = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      const { tagIds } = await parseBody(req, setTagsSchema);
      await setClientTags(params.id!, ctx.portId, tagIds, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
