import { getGeneralSettings } from "@/models/settings";
import { response } from "@/utils/helper";
import { headers } from "next/headers";
import { NextResponse } from "next/server";

export async function joinBridgeMiddleware(request) {
  try {
    // check join bridge is enabled
    const generalSettings = await getGeneralSettings();

    if (!generalSettings?.bridge)
      return NextResponse.json(
        { error: "Join bridge is disabled" },
        { status: 403 }
      );

    if (request.url.includes("posts")) {
      const header = await headers();
      const authorization = header.get("authorization");

      if (!authorization) {
        return response(401, "Unauthorized", null, {
          error: "Authorization not found",
        });
      }
    }

    return NextResponse.next();
  } catch (error) {
    return NextResponse.json(
      { error: error?.message || error },
      { status: 500 }
    );
  }
}
