import { createHash } from "crypto";
import { withDb, AppDatabase } from "../db";
import { convert } from "../lib/media-convert";

interface VoiceLineAudioUpdateTaskOptions {
  voiceLineId: string;
}

const sha1sum = (v: any) => {
  const shasum = createHash("sha1");
  shasum.update(v);
  return shasum.digest("hex");
};

const voiceLineAudioUpdateTask = async (
  payload: VoiceLineAudioUpdateTaskOptions
): Promise<void> =>
  withDb(async (db: AppDatabase) => {
    const { voiceLineId } = payload;
    const voiceLine = await db.voiceLines.findById({ id: voiceLineId });
    if (!voiceLine) return;
    if (!voiceLine?.promptAudio?.["audio/webm"]) return;

    const webm = Buffer.from(voiceLine.promptAudio["audio/webm"], "base64");
    const webmSha1 = sha1sum(webm);

    if (
      voiceLine.promptAudio.checksum &&
      voiceLine.promptAudio.checksum === webmSha1
    ) {
      // already converted
      return;
    }

    const mp3 = await convert(webm);
    await db.voiceLines.updateById(
      { id: voiceLine.id },
      {
        promptAudio: {
          ...voiceLine.promptAudio,
          "audio/mpeg": mp3.toString("base64"),
          checksum: webmSha1,
        },
      }
    );
  });

export default voiceLineAudioUpdateTask;
