import { NextRequest, NextResponse } from "next/server";
import { Service } from "./service";
import { db, getWorkerUtils } from "@link-stack/bridge-common";

export class Facebook extends Service {
  async handleWebhook(req: NextRequest) {
    const { searchParams } = req.nextUrl;
    const submittedToken = searchParams.get("hub.verify_token");

    if (submittedToken) {
      await db
        .selectFrom("FacebookBot")
        .selectAll()
        .where("verifyToken", "=", submittedToken)
        .executeTakeFirstOrThrow();

      if (searchParams.get("hub.mode") === "subscribe") {
        const challenge = searchParams.get("hub.challenge");
        const response = new Response(challenge, { status: 200 });

        return response as any;
      } else {
        return NextResponse.error();
      }
    } else {
      const message = await req.json();
      const worker = await getWorkerUtils();
      await worker.addJob("facebook/receive-facebook-message", { message });

      return NextResponse.json({ response: "ok" });
    }
  }
}
