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

export async function POST(request) {
  try {
    const body = await request.json();

    if (!body?.data || !body?.data?.ID || !body?.data?.ID.startsWith("ICETEA-"))
      return response(400, "Bad Request", null, { error: "Invalid request" });

    const general = await getGeneralSettings();

    if (!general?.CMS_ID)
      return response(403, "Forbidden", null, {
        error: "Join bridge not allowed",
      });

    const data = {
      ID: body.data.ID,
      timestamp: new Date().toISOString(),
      OWN_ID: general.CMS_ID,
    };

    const API_KEY = new Encryption().encrypt(JSON.stringify(data));
    return response(200, "Auth success", { API_KEY });
  } catch (error) {
    console.log(error);
    return response(500, "Internal Server Error", null, {
      error: "Auth failed",
    });
  }
}
