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 { createClientGroup, listClientGroups } from '@/lib/services/client-groups.service';
import { createClientGroupSchema } from '@/lib/validators/client-groups';

export const listHandler: RouteHandler = async (req, ctx) => {
  try {
    const groups = await listClientGroups(ctx.portId);
    return NextResponse.json({ data: groups, total: groups.length });
  } catch (error) {
    return errorResponse(error);
  }
};

export const createHandler: RouteHandler = async (req, ctx) => {
  try {
    const body = await parseBody(req, createClientGroupSchema);
    const group = await createClientGroup(ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: group }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
};
