import { NextResponse } from 'next/server';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listGroupMembers, setGroupMembers } from '@/lib/services/client-groups.service';
import { setGroupMembersSchema } from '@/lib/validators/client-groups';

export const getMembersHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const members = await listGroupMembers(params.id!, ctx.portId);
    return NextResponse.json({ data: members, total: members.length });
  } catch (error) {
    return errorResponse(error);
  }
};

export const putMembersHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const { clientIds } = await parseBody(req, setGroupMembersSchema);
    await setGroupMembers(params.id!, ctx.portId, clientIds, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    return errorResponse(error);
  }
};
