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

const linkBerthSchema = z.object({
  berthId: z.string().min(1),
});

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

export const DELETE = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const interest = await unlinkBerth(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: interest });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
