60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { db } from "@link-stack/bridge-common";
|
|
import { revalidatePath } from "next/cache";
|
|
import { Service, ServiceParams } from "./service";
|
|
|
|
export class Whatsapp extends Service {
|
|
async getBot({ params }: ServiceParams) {
|
|
const { token } = await params;
|
|
const row = await db
|
|
.selectFrom("WhatsappBot")
|
|
.selectAll()
|
|
.where("token", "=", token as string)
|
|
.executeTakeFirstOrThrow();
|
|
const id = row.id;
|
|
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}`;
|
|
const result = await fetch(url, { cache: "no-store" });
|
|
const json = await result.json();
|
|
|
|
await db
|
|
.updateTable("WhatsappBot")
|
|
.set({ verified: json.verified })
|
|
.where("id", "=", id)
|
|
.execute();
|
|
|
|
if (!json.verified) {
|
|
const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/register`;
|
|
const result = await fetch(url, { method: "POST" });
|
|
}
|
|
|
|
revalidatePath(`/whatsapp/${id}`);
|
|
|
|
return NextResponse.json(json);
|
|
}
|
|
|
|
async relink({ params }: ServiceParams) {
|
|
const { token } = await params;
|
|
const row = await db
|
|
.selectFrom("WhatsappBot")
|
|
.selectAll()
|
|
.where("token", "=", token as string)
|
|
.executeTakeFirstOrThrow();
|
|
const id = row.id;
|
|
|
|
// Step 1: Call unverify to remove the bot directory and disconnect
|
|
const unverifyUrl = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${id}/unverify`;
|
|
await fetch(unverifyUrl, { method: "POST" });
|
|
|
|
// Step 2: Reset verified flag in database
|
|
await db
|
|
.updateTable("WhatsappBot")
|
|
.set({ verified: false })
|
|
.where("id", "=", id)
|
|
.execute();
|
|
|
|
// Step 3: Revalidate the path to refresh the UI
|
|
revalidatePath(`/whatsapp/${id}`);
|
|
|
|
return NextResponse.json({ success: true, message: "WhatsApp connection reset. Please scan the new QR code." });
|
|
}
|
|
}
|