"use node";

import { action } from "./_generated/server";
import { v } from "convex/values";
import { AccessToken } from "livekit-server-sdk";

// Generate LiveKit token for voice channel
export const getToken = action({
  args: {
    channelId: v.string(),
    userId: v.string(),
    username: v.string(),
  },
  returns: v.object({ token: v.string() }),
  handler: async (_ctx, args) => {
    const apiKey = process.env.LIVEKIT_API_KEY || "devkey";
    const apiSecret = process.env.LIVEKIT_API_SECRET || "secret";

    const at = new AccessToken(apiKey, apiSecret, {
      identity: args.userId,
      name: args.username,
      ttl: "24h",
    });

    at.addGrant({
      roomJoin: true,
      room: args.channelId,
      canPublish: true,
      canSubscribe: true,
      canPublishData: true,
    });

    const token = await at.toJwt();
    return { token };
  },
});
