import { exec } from 'child_process';
import { cache } from 'react';

export type Post = {
  title: string;
  message?: string;
  author: {
    email: string;
    name: string;
  };
  time: number;
};

export const getPosts = cache(async (): Promise<Post[]> => {
  const updatePosts = async () => {
    return new Promise((resolve, reject) => {
      exec(
        `(cd  ${process.env.POSTS_DIR}; git pull --rebase || true)`,
        (error, stdout, stderr) => {
          if (error) {
            console.warn(error);
            reject(
              'could not update posts stderr: ' + stderr + 'stdout: ' + stdout,
            );
            return;
          }

          resolve(true);
        },
      );
    });
  };

  await updatePosts();

  return new Promise((resolve, reject) => {
    exec(`git-log --path ${process.env.POSTS_DIR}`, (error, stdout, stderr) => {
      if (error) {
        console.warn(error);
        reject('could not load posts stderr: ' + stderr + 'stdout: ' + stdout);
        return;
      }

      const posts: Post[] = JSON.parse(stdout);

      resolve(posts);
    });
  });
});
