"use node";

import { v } from "convex/values";
import { action } from "./_generated/server";
import { internal } from "./_generated/api";
import { createClerkClient } from "@clerk/backend";

export const inviteAdmin = action({
  args: {
    email: v.string(),
    role: v.union(v.literal("admin"), v.literal("super_admin")),
  },
  handler: async (ctx, { email, role }) => {
    await ctx.runQuery(internal.users.assertSuperAdmin);

    const clerk = createClerkClient({
      secretKey: process.env.CLERK_ADMIN_SECRET_KEY!,
    });

    await clerk.invitations.createInvitation({
      emailAddress: email,
      redirectUrl: `${process.env.ADMIN_URL}/sign-in`,
      publicMetadata: { role },
    });
  },
});
