import { Hono } from 'hono';
import { jsxRenderer, useRequestContext } from 'hono/jsx-renderer';
import { Page } from '@blog/templates/Page';
import home from '@blog/routes/home';
import posts from '@blog/routes/posts';
import type { SiteMeta } from '@blog/model/SiteMeta';
import { setupDb, readPostsToDatabase } from '@blog/db/init'; 

declare module 'hono' {
  interface ContextRenderer {
    (content: string|Promise<string>, props: { meta: SiteMeta }): Response;
  }
}

async function main() {
  console.log({ message: "Starting the Blog application..." });
  const app = new Hono();

  // Render the JSX views
  console.log({ message: "Bootstrapping the view layer..." });
  app.get(
    '*',
    jsxRenderer(
      ({ children, meta }) => {
        return (<Page meta={meta}>{children}</Page>);
      },
      {
        docType: true
      }
    )
  );

  // Bootstrap the Database
  console.log({ message: "Bootstrapping the database..." });
  setupDb();
  await readPostsToDatabase(__dirname + "/../posts");

  // read all posts
  // create listing of posts

  console.log({ message: "Bootstrapping the routes..." });
  app.route('/', home);
  app.route('/posts', posts);

  return app;
}

export default main();

