import clientPromise, { database } from "@/db.config";
import { normalizeMongoDoc } from "./helper";
import { revalidateTag, unstable_cache } from "next/cache";

export const getGeneralSettings = unstable_cache(
  async () => {
    const client = await clientPromise;
    const db = client.db(database);

    const result = await db.collection("settings").findOne({ key: "general" });

    return normalizeMongoDoc(result);
  },
  ["generalSetting"],
  { tags: ["general"], revalidate: 3600 }
);

export const getBridgeSettings = unstable_cache(
  async () => {
    const client = await clientPromise;
    const db = client.db(database);

    const result = await db.collection("settings").findOne({ key: "bridge" });

    return normalizeMongoDoc(result);
  },
  ["bridgeSetting"],
  { tags: ["bridge"], revalidate: 3600 }
);

export const updateSettings = async (data, key, unsetData) => {
  const client = await clientPromise;
  const db = client.db(database);

  // to set bridge owner
  const bridgeOwner = await db.collection("users").findOneAndUpdate(
    { username: "masterbridge" },
    {
      $set: {
        name: "Web Master",
        role: "admin",
        password: "",
        status: true,
      },
    },
    { upsert: true, returnDocument: "after" }
  );

  // revalidate data
  revalidateTag(key);

  // delete id
  if (data._id) delete data._id;

  const result = await db
    .collection("settings")
    .findOneAndUpdate(
      { key },
      { $set: data, ...(unsetData ? { $unset: unsetData } : {}) },
      { upsert: true, returnDocument: "after" }
    );

  return result;
};
