import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { getUser, updateUser, removeUserFromPort } from '@/lib/services/users.service';
import { updateUserSchema } from '@/lib/validators/users';
import { errorResponse } from '@/lib/errors';

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

export const PATCH = withAuth(
  withPermission('admin', 'manage_users', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateUserSchema);
      const data = await updateUser(
        params.id!,
        ctx.portId,
        body,
        {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
        ctx.permissions as Record<string, Record<string, boolean>> | null,
        ctx.isSuperAdmin,
      );
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_users', async (_req, ctx, params) => {
    try {
      await removeUserFromPort(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
