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

interface VoiceLineDeleteTaskOptions {
  voiceLineId: string;
  providerId: string;
  providerLineSid: string;
}

const voiceLineDeleteTask = async (
  payload: VoiceLineDeleteTaskOptions
): Promise<void> =>
  withDb(async (db: AppDatabase) => {
    const { voiceLineId, providerId, providerLineSid } = payload;
    const provider = await db.voiceProviders.findById({ id: 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,
    });

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

export default voiceLineDeleteTask;
