import { Client } from "ldapts";

import { Term } from "@/utils";

export interface Member {
  name: string;
  id: string;
  program: string;
}

export async function getMembers(year: string, term: Term): Promise<Member[]> {
  if (process.env.USE_LDAP?.toLowerCase() !== "true") {
    return dummyMembers;
  }
  let members: Member[] = [];

  const url = "ldap://ldap1.csclub.uwaterloo.ca";
  const searchDN = "ou=People,dc=csclub,dc=uwaterloo,dc=ca";
  const client = new Client({ url });

  try {
    await client.bind("", "");
    const { searchEntries } = await client.search(searchDN, {
      scope: "sub",
      filter: `(&(objectClass=member)(term=${(term as string).slice(
        0,
        1
      )}${year}))`,
    });

    members = searchEntries
      .map((item) => {
        return {
          name: item.cn as string,
          id: item.uid as string,
          program: item.program === undefined ? "" : (item.program as string),
        };
      })
      .sort((item1: Member, item2: Member) =>
        item1.name.localeCompare(item2.name)
      );
  } finally {
    await client.unbind();
  }

  return members;
}

const dummyMembers: Member[] = [
  {
    name: "John Smith",
    id: "j12smith",
    program: "MAT/Mathematics Computer Science",
  },
  {
    name: "Jane Smith",
    id: "j34smith",
    program: "MAT/Mathematics Computer Science",
  },
];
