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

export async function GET(request) {
  try {
    // get header
    const header = await headers();
    const authorization = header.get("authorization");

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

    const bearer = authorization.split("Bearer ")[1];

    const general = await getGeneralSettings();
    const notAllowedRes = response(403, "Forbidden", null, {
      error: "Join bridge not allowed",
    });

    if (!general?.CMS_ID) return notAllowedRes;

    const decryptedData = new Encryption().decrypt(bearer);
    const data = JSON.parse(decryptedData);

    if (data?.OWN_ID !== general.CMS_ID) return notAllowedRes;

    return response(200, "Connection Ready", { access: "grant" });
  } catch (error) {
    return response(500, "Internal Server Error", null, { error });
  }
}
