import { action } from "../_generated/server";
import { v } from "convex/values";

/**
 * Send a WhatsApp message via Twilio API
 * Phase 6: WhatsApp & Voice Agents
 */
export const sendViaTwilio = action({
  args: {
    to: v.string(),
    body: v.string(),
    from: v.string(),
    twilioAccountSid: v.string(),
    twilioAuthToken: v.string(),
  },
  handler: async (_ctx, args) => {
    const url = `https://api.twilio.com/2010-04-01/Accounts/${args.twilioAccountSid}/Messages.json`;
    const credentials = btoa(
      `${args.twilioAccountSid}:${args.twilioAuthToken}`,
    );

    const response = await fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Basic ${credentials}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        To: `whatsapp:${args.to}`,
        From: `whatsapp:${args.from}`,
        Body: args.body,
      }).toString(),
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Twilio API error (${response.status}): ${error}`);
    }

    const result = await response.json();
    return { sid: result.sid, status: result.status };
  },
});
