import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { getPort, updatePort } from '@/lib/services/ports.service';
import { updatePortSchema } from '@/lib/validators/ports';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, _ctx, params) => {
    try {
      const data = await getPort(params.id!);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updatePortSchema);
      const data = await updatePort(params.id!, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
