import { Client } from "@notionhq/client";

const notion = new Client({
  auth: process.env.NOTION_TOKEN,
});

export const getDatabase = async (databaseId) => {
  const response = await notion.databases.query({
    database_id: databaseId,
  });

  const database = response.results;

  // Filter posts to keep only those with required attributes
  // Name = not empty, Publish = true, PostDate is not empty
  var database_filtered = database
    .filter((post) => {
      // Empty post title
      if (post.properties.Name.title.length === 0) {
        return false;
      }
      // Publish checkbox not checked
      if (!post.properties.Publish.checkbox) {
        return false;
      }
      // Post date not set
      if (!("PostDate" in post.properties)) {
        return false;
      }
      return true;
    })
    .sort(
      (post1, post2) =>
        new Date(post2.properties.PostDate.date.start) -
        new Date(post1.properties.PostDate.date.start)
    );
  database_filtered.forEach((post) => {
    post.slug = post.properties.slug.formula.string + "-" + post.id;
  });

  return database_filtered;
};

export const getPage = async (pageId) => {
  const response = await notion.pages.retrieve({ page_id: pageId });
  return response;
};

export const getBlocks = async (blockId, start_cursor) => {
  const response = await notion.blocks.children.list({
    block_id: blockId,
    page_size: 100,
    start_cursor: start_cursor,
  });
  if (response.has_more) {
    var extra_elements = await getBlocks(blockId, response.next_cursor);
    response.results.push(...extra_elements);
  }
  return response.results;
};
