import { NextResponse } from 'next/server';

import { requireSuperAdmin, withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { listPorts, createPort } from '@/lib/services/ports.service';
import { createPortSchema } from '@/lib/validators/ports';
import { errorResponse } from '@/lib/errors';

// Listing every tenant and creating new tenants are super-admin operations:
// a port director must not be able to enumerate other ports (target
// discovery for cross-tenant attacks) or spin up new tenants whose admin
// they implicitly become.
export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      requireSuperAdmin(ctx, 'admin.ports.list');
      const data = await listPorts();
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      requireSuperAdmin(ctx, 'admin.ports.create');
      const body = await parseBody(req, createPortSchema);
      const data = await createPort(body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
