import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { getRole, updateRole, deleteRole } from '@/lib/services/roles.service';
import { updateRoleSchema } from '@/lib/validators/roles';
import { errorResponse } from '@/lib/errors';

export const GET = withAuth(
  withPermission('admin', 'manage_users', async (_req, _ctx, params) => {
    try {
      const data = await getRole(params.id!);
      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, updateRoleSchema);
      const data = await updateRole(params.id!, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_users', async (_req, ctx, params) => {
    try {
      await deleteRole(params.id!, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ success: true });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
