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

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

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

// PUT /api/v1/berths/[id]/tags
export const PUT = withAuth(
  withPermission('berths', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, setTagsSchema);
      const result = await setBerthTags(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);
    }
  }),
);
