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

/*
 * VoiceProvider
 *
 * A provider is a company that provides incoming voice call services
 */

export type VoiceProviderId = Flavor<UUID, "VoiceProvider Id">;

export enum VoiceProviderKinds {
  TWILIO = "TWILIO",
}

export type TwilioCredentials = {
  accountSid: string;
  apiKeySid: string;
  apiKeySecret: string;
};

// expand this type later when we support more providers
export type VoiceProviderCredentials = TwilioCredentials;

export interface UnsavedVoiceProvider {
  kind: VoiceProviderKinds;
  name: string;
  credentials: VoiceProviderCredentials;
}

export interface SavedVoiceProvider extends UnsavedVoiceProvider {
  id: VoiceProviderId;
  createdAt: Date;
  updatedAt: Date;
}

export const VoiceProviderRecord = recordInfo<
  UnsavedVoiceProvider,
  SavedVoiceProvider
>("app_public", "voice_providers");

export class VoiceProviderRecordRepository extends RepositoryBase(
  VoiceProviderRecord
) {
  async findByTwilioAccountSid(
    accountSid: string
  ): Promise<SavedVoiceProvider | null> {
    return this.db.oneOrNone(
      "select * from $1 where credentials->>'accountSid' = $2",
      [this.schemaTable, accountSid]
    );
  }
}
