import { app } from "@/firebase";
import { CorporateUser, StudentUser, TeacherUser } from "@/interfaces/user";
import { doc, getDoc, getFirestore, setDoc } from "firebase/firestore";
import moment from "moment";

const db = getFirestore(app);

export const updateExpiryDateOnGroup = async (
  participantID: string,
  corporateID: string,
) => {
  const corporateRef = await getDoc(doc(db, "users", corporateID));
  const participantRef = await getDoc(doc(db, "users", participantID));

  if (!corporateRef.exists() || !participantRef.exists()) return;

  const corporate = {
    ...corporateRef.data(),
    id: corporateRef.id,
  } as CorporateUser;
  const participant = { ...participantRef.data(), id: participantRef.id } as
    | StudentUser
    | TeacherUser;

  if (
    corporate.type !== "corporate" ||
    (participant.type !== "student" && participant.type !== "teacher")
  )
    return;

  if (
    !corporate.subscriptionExpirationDate ||
    !participant.subscriptionExpirationDate
  ) {
    return await setDoc(
      doc(db, "users", participant.id),
      { subscriptionExpirationDate: null },
      { merge: true },
    );
  }

  const corporateDate = moment(corporate.subscriptionExpirationDate);
  const participantDate = moment(participant.subscriptionExpirationDate);

  if (corporateDate.isAfter(participantDate))
    return await setDoc(
      doc(db, "users", participant.id),
      { subscriptionExpirationDate: corporateDate.toISOString() },
      { merge: true },
    );

  return;
};
