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, ForbiddenError } from '@/lib/errors';

/**
 * Non-super-admin callers (e.g. port directors holding admin.manage_settings)
 * may only read/mutate THEIR OWN port row. The path id is therefore
 * compared against ctx.portId and a foreign target is rejected before the
 * service is touched. Super-admins retain unrestricted access.
 */
function assertPortInScope(targetPortId: string, ctx: { portId: string; isSuperAdmin: boolean }) {
  if (ctx.isSuperAdmin) return;
  if (targetPortId !== ctx.portId) {
    throw new ForbiddenError('Cross-tenant port access denied');
  }
}

export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      assertPortInScope(params.id!, ctx);
      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 {
      assertPortInScope(params.id!, ctx);
      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);
    }
  }),
);
