import {
  RepositoryBase,
  recordInfo,
  UUID,
  Flavor,
} from "@digiresilience/metamigo-common";
import type {} from "pg-promise";

export type VoiceLineId = Flavor<UUID, "VoiceLine Id">;

export type VoiceLineAudio = {
  "audio/webm": string;
  "audio/mpeg"?: string;
  checksum?: string;
};

export interface UnsavedVoiceLine {
  providerId: string;
  providerLineSid: string;
  number: string;
  language: string;
  voice: string;
  promptText?: string;
  promptAudio?: VoiceLineAudio;
  audioPromptEnabled: boolean;
  audioConvertedAt?: Date;
}

export interface SavedVoiceLine extends UnsavedVoiceLine {
  id: VoiceLineId;
  createdAt: Date;
  updatedAt: Date;
}

export const VoiceLineRecord = recordInfo<UnsavedVoiceLine, SavedVoiceLine>(
  "app_public",
  "voice_lines"
);

export class VoiceLineRecordRepository extends RepositoryBase(VoiceLineRecord) {
  /**
   * Fetch all voice lines given the numbers
   * @param numbers
   */
  async findAllByNumbers(numbers: string[]): Promise<SavedVoiceLine[]> {
    return this.db.any(
      "SELECT id,provider_id,provider_line_sid,number FROM $1 WHERE number in ($2:csv)",
      [this.schemaTable, numbers]
    );
  }

  /**
   * Fetch all voice lines given a list of provider line ids
   * @param ids
   */
  async findAllByProviderLineSids(ids: string[]): Promise<SavedVoiceLine[]> {
    return this.db.any(
      "SELECT id,provider_id,provider_line_sid,number FROM $1 WHERE provider_line_sid in ($2:csv)",
      [this.schemaTable, ids]
    );
  }
}
