import { Handlers, PageProps } from "$fresh/server.ts";
import { query } from "../db.ts";

interface Note {
  id: string;
  created_at: Date;
  content: string;
}

export const handler: Handlers<Note[] | null> = {
  async GET(request, context) {
    console.debug({ request, context });
    const result = await query("select * from notes");
    if (result == null) throw "unable to fetch from database";
    const notes = result.rows as Note[];
    console.debug(notes);
    return await context.render(notes);
  },
};

export default function Page({ data }: PageProps<Note[] | null>) {
  return (
    <div>
      <h1>List of Notes</h1>
      <nav>
        <a href="/" class="text-blue-500 p-2">Back to Index</a>
      </nav>
      <p>Create a note:</p>
      <form action="./create" method="POST">
        <textarea name="content"></textarea>
        <button>Post</button>
      </form>
      <pre>
        {JSON.stringify(data, null, 2)}
      </pre>
    </div>
  );
}
