import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { listUsers, createUser } from '@/lib/services/users.service';
import { createUserSchema } from '@/lib/validators/users';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_users', async (_req, ctx) => {
    try {
      const data = await listUsers(ctx.portId);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

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