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 { setInterestTags } from '@/lib/services/interests.service';

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

export const PUT = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, setTagsSchema);
      const result = await setInterestTags(params.id!, ctx.portId, body.tagIds, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
