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 {
  archiveClientGroup,
  getClientGroupById,
  updateClientGroup,
} from '@/lib/services/client-groups.service';
import { updateClientGroupSchema } from '@/lib/validators/client-groups';

export const getHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const group = await getClientGroupById(params.id!, ctx.portId);
    return NextResponse.json({ data: group });
  } catch (error) {
    return errorResponse(error);
  }
};

export const patchHandler: RouteHandler = async (req, ctx, params) => {
  try {
    const body = await parseBody(req, updateClientGroupSchema);
    const updated = await updateClientGroup(params.id!, ctx.portId, body, {
      userId: ctx.userId,
      portId: ctx.portId,
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });
    return NextResponse.json({ data: updated });
  } catch (error) {
    return errorResponse(error);
  }
};

export const deleteHandler: RouteHandler = async (req, ctx, params) => {
  try {
    await archiveClientGroup(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);
  }
};
