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

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

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