import { DOMParser } from "jsr:@b-fuze/deno-dom";
import { wrapFetch } from "jsr:@jd1378/another-cookiejar@^5.0.7";
import * as cli from "jsr:@std/cli";

const flags = cli.parseArgs(Deno.args, {
  string: ["email", "password", "search"],
});
const fetch = wrapFetch();

const email = flags.email || Deno.env.get("CBTW_EMAIL") ||
  prompt("Please enter your email:") || "";
const password = flags.password || Deno.env.get("CBTW_PASSWORD") ||
  cli.promptSecret("Please enter your password:") || "";

export async function mitarbeiterangebote() {
  await fetch(
    "https://cbtw.mitarbeiterangebote.de/login",
    {
      method: "POST",
      body: new URLSearchParams({
        "loginData[email]": email,
        "loginData[password]": password,
      }),
    },
  );
  await fetch("https://cbtw.mitarbeiterangebote.de/", {
    method: "POST",
    body: new URLSearchParams({
      "platformData[disclaimerNewsletter]": "0",
      "disclaimerAccept": "1",
    }),
  });

  const res = await fetch("https://cbtw.mitarbeiterangebote.de/overview/23");
  const html = await res.text();
  const document = new DOMParser().parseFromString(html, "text/html");

  return Array.from(document.querySelectorAll(".cbg3-offer-list-item--content"))
    .map(
      (element) => {
        const title = element.querySelector("a[title]")
          ?.getAttribute("title")?.replace("Zum Angebot: ", "") || "";
        const description = element.querySelector(
              "p.cbg3-list-item--copy",
            )?.textContent?.trim().substring(0, 50) + "..." || "";
        const discount = element.querySelector(
          "div.cbg3-list-item--discount p",
        )?.textContent?.trim() || "";

        return { title, description, discount };
      },
    ).filter((offer, index, self) =>
      index === self.findIndex((o) => o.title === offer.title)
    ).sort((a, b) => a.title.localeCompare(b.title));
}

const offers = await mitarbeiterangebote();
if (flags.search) {
  const filtered = offers.filter((offer) =>
    offer.title.toLowerCase().includes(flags.search!.toLowerCase())
  );
  console.table(filtered);
} else {
  console.table(offers);
}
