import clientPromise, { database, objectId } from "@/db.config";
import { getOrigin, modifyByKeys, normalizeMongoDoc } from "./helper";
import { deleteFile, spliceObject } from "@/utils/library";

export const getGallery = async (
  { page = 1, limit = 100 },
  sort = { createdAt: -1 },
  search = null
) => {
  const client = await clientPromise;
  const mongo = client.db(database);
  const media = mongo.collection("media");
  const origin = await getOrigin();

  const [result, total] = await Promise.all([
    await media
      .aggregate([
        {
          $match: search
            ? {
                $or: [
                  { title: { $regex: search, $options: "i" } },
                  { alt: { $regex: search, $options: "i" } },
                ],
              }
            : {},
        },
        { $sort: sort },
        { $skip: (page - 1) * limit },
        { $limit: limit },
      ])
      .toArray(),
    await media.countDocuments(),
  ]);
  const data = normalizeMongoDoc(result)?.map((data) =>
    // modifyByKeys(data, ["url"], (url) => `${origin}/api${url}`, true)
    modifyByKeys(data, ["url"], (url) => `${origin}${url}`, true)
  );
  const totalPage = Math.ceil(total / limit);
  return { page, limit, total, totalPage, data, keyword: search };
};

export const updateGalleryById = async (data) => {
  const client = await clientPromise;
  const mongo = client.db(database);
  const media = mongo.collection("media");
  const origin = await getOrigin();

  const { selected, spliced } = spliceObject(data, ["_id", "createdAt"]);
  const id = objectId(selected._id);

  await media.updateOne({ _id: id }, { $set: spliced });
  const result = await media.findOne({ _id: id });

  return modifyByKeys(
    normalizeMongoDoc(result),
    ["url"],
    // (url) => `${origin}/api${url}`
    (url) => `${origin}${url}`
  );
};

export const searchMedia = async (keyword) => {
  const client = await clientPromise;
  const mongo = client.db(database);
  const media = mongo.collection("media");

  const data = await media
    .find({
      $or: [
        { title: { $regex: keyword, $options: "i" } },
        { alt: { $regex: keyword, $options: "i" } },
      ],
    })
    .sort({ createdAt: -1 })
    .toArray();

  return modifyByKeys(
    normalizeMongoDoc(data),
    ["url"],
    // (url) => `${origin}/api${url}`
    (url) => `${origin}${url}`
  );
};

export const deleteMedia = async (id) => {
  const client = await clientPromise;
  const mongo = client.db(database);
  const media = mongo.collection("media");

  const currentData = await media.findOne({ _id: objectId(id) });
  await media.deleteOne({ _id: objectId(id) });

  // delete from media folder
  deleteFile(currentData.url);

  return normalizeMongoDoc(currentData);
};
