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

export type WhatsappBotId = Flavor<UUID, "Whatsapp Bot Id">;

export interface UnsavedWhatsappBot {
  phoneNumber: string;
  userId: string;
  description: string;
}

export interface SavedWhatsappBot extends UnsavedWhatsappBot {
  id: WhatsappBotId;
  createdAt: Date;
  updatedAt: Date;
  token: string;
  authInfo: string;
  qrCode: string;
  isVerified: boolean;
}

export const WhatsappBotRecord = recordInfo<
  UnsavedWhatsappBot,
  SavedWhatsappBot
>("app_public", "whatsapp_bots");

export class WhatsappBotRecordRepository extends RepositoryBase(
  WhatsappBotRecord
) {
  async updateQR(
    bot: SavedWhatsappBot,
    qrCode: string | undefined
  ): Promise<SavedWhatsappBot> {
    return this.db.one(
      "UPDATE $1 SET (qr_code) = ROW($2) WHERE id = $3 RETURNING *",
      [this.schemaTable, qrCode, bot.id]
    );
  }

  async updateVerified(
    bot: SavedWhatsappBot,
    verified: boolean
  ): Promise<SavedWhatsappBot> {
    return this.db.one(
      "UPDATE $1 SET (is_verified) = ROW($2) WHERE id = $3 RETURNING *",
      [this.schemaTable, verified, bot.id]
    );
  }
}
