import { readFileSync } from "node:fs";
import fetch from "node-fetch";

class CreateListmonkCampaign {
  constructor() {
    this.run();
  }

  async run() {
    let postNumber = `00000${readFileSync("site/post/count", "utf8")}`.slice(
      -6
    );
    let postData = readFileSync(`site/post/${postNumber}.md`, "utf8");

    let title = postData.slice(postData.indexOf("## ") + 3);
    title = title.slice(0, title.indexOf("\n"));

    let imageUrl = postData.slice(postData.indexOf("](/") + 3);
    imageUrl = imageUrl.slice(0, imageUrl.indexOf(")"));
    imageUrl = `https://xn--trupgrd-exae.com/${imageUrl}`;

    let contentBody = `
      <h1>${title}</h1>
      <a href="https://xn--trupgrd-exae.com@TrackLink">
        <img src=\"${imageUrl}\">
      </a>
      <a class="button" href="https://xn--trupgrd-exae.com@TrackLink">View Post</a>
    `;

    let createRequestBody = {
      name: title,
      subject: "New Post",
      lists: [process.env.INPUT_IS_PRODUCTION == "true" ? 3 : 4],
      from_email: "TårupGård Mailer <mailer@tarupgard.com>",
      content_type: "html",
      type: "regular",
      template_id: 1,
      body: contentBody,
    };

    console.log(process.env.INPUT_LISTMONK_USER);

    let requestHeaders = {
      Authorization:
        "Basic " +
        Buffer.from(
          `${process.env.INPUT_LISTMONK_USER}:${process.env.INPUT_LISTMONK_PASS}`
        ).toString("base64"),
      "Content-Type": "application/json;charset=utf-8",
    };

    let createResponse = await fetch(
      "https://mailer.tarupgard.com/api/campaigns",
      {
        method: "POST",
        headers: requestHeaders,
        body: JSON.stringify(createRequestBody),
      }
    );

    let campaignId = (await createResponse.json()).data.id;

    await fetch(
      `https://mailer.tarupgard.com/api/campaigns/${campaignId}/status`,
      {
        method: "PUT",
        headers: requestHeaders,
        body: JSON.stringify({
          status: "running",
        }),
      }
    );
  }
}

new CreateListmonkCampaign();

// COMMIT_MESSAGE="$(git log)"
// if [[ $COMMIT_MESSAGE == *"__post__"* ]]; then
//   [[ ${COMMIT_MESSAGE} =~ __post__([[:digit:]]{6}) ]] && POST_NUMBER=${BASH_REMATCH[1]}

//   echo $POST_NUMBER
//   TITLE=$(cat site/post/$POST_NUMBER.md | grep "\#\#\ ")
//   TITLE=${TITLE:3}
//   IMAGE_URL=https://xn--trupgrd-exae.com/$(cat site/post/$POST_NUMBER.md | grep "_01.jpg" | grep -oP '(?<=\]\().*?(?=\))')
//   # curl -u "$INPUT_LISTMONK_USER:$INPUT_LISTMONK_PASS" -X GET 'https://mailer.tarupgard.com/api/campaigns?page=1&per_page=100'
// fi
