import Twilio from "twilio";
import config from "@digiresilience/metamigo-config";
import { withDb, AppDatabase } from "../db";

interface VoiceLineUpdateTaskOptions {
  voiceLineId: string;
}

const voiceLineUpdateTask = async (
  payload: VoiceLineUpdateTaskOptions
): Promise<void> =>
  withDb(async (db: AppDatabase) => {
    const { voiceLineId } = payload;
    const voiceLine = await db.voiceLines.findById({ id: voiceLineId });
    if (!voiceLine) return;

    const provider = await db.voiceProviders.findById({
      id: voiceLine.providerId,
    });
    if (!provider) return;

    const { accountSid, apiKeySid, apiKeySecret } = provider.credentials;
    if (!accountSid || !apiKeySid || !apiKeySecret)
      throw new Error(
        `twilio provider ${provider.name} does not have credentials`
      );

    const client = Twilio(apiKeySid, apiKeySecret, {
      accountSid,
    });

    await client.incomingPhoneNumbers(voiceLine.providerLineSid).update({
      voiceUrl: `${config.frontend.url}/api/v1/voice/twilio/record/${voiceLineId}`,
      voiceMethod: "POST",
    });
  });

export default voiceLineUpdateTask;
