import clientPromise, { database, objectId } from "@/db.config";
import { normalizeMongoDoc, parseToObjectId } from "./helper";
import { parseDateValue } from "@/utils/library";

export const updateJadwalPelatihan = async (data) => {
  const client = await clientPromise;
  const db = client.db(database);
  const _id = objectId(data?._id);

  // remove _id from data to prevent immutable field update error
  if (!data?._id) {
    const resultDb = await db
      .collection("jadwal_pelatihan")
      .insertOne(parseToObjectId(parseDateValue(data), ["post_id"]));
    const result = await db
      .collection("jadwal_pelatihan")
      .findOne({ _id: resultDb.insertedId });

    return normalizeMongoDoc(result);
  }

  delete data._id;
  const result = await db
    .collection("jadwal_pelatihan")
    .findOneAndUpdate(
      { _id },
      { $set: parseToObjectId(parseDateValue(data), ["post_id"]) },
      { returnDocument: "after" }
    );

  return normalizeMongoDoc(result);
};

export const getJadwalPelatihanByPostId = async (id) => {
  const client = await clientPromise;
  const db = client.db(database);
  const oneMonthAgo = new Date();
  oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
  const result = await db
    .collection("jadwal_pelatihan")
    .find({ post_id: objectId(id), date_end: { $gt: oneMonthAgo } })
    .toArray();
  return normalizeMongoDoc(result);
};

export const deleteJadwalPelatihanById = async (id) => {
  const client = await clientPromise;
  const db = client.db(database);
  return await db
    .collection("jadwal_pelatihan")
    .deleteOne({ _id: objectId(id) });
};
