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

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

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

export default function NotesPage({ data: notes }: PageProps<Note[]>) {
  return (
    <Page>
      <h1>List of Notes</h1>
      <p>Create a note:</p>
      <form class="flex flex-col" action="./note/create" method="POST">
        <textarea rows={6} class="" name="content">
        </textarea>
        <input class="mt-2" type="submit" value="Post" />
      </form>
      {notes.map(({ id, content, created_at }) => (
        <div class="my-4" key={id}>
          <span>
            <a href={`/note/${id}`} class="text-blue-500">Note {id}</a>{" "}
            created at {created_at.toLocaleString()}
          </span>
          <blockquote class="mt-2 pl-4 border-l(solid 4)">
            <pre>{content}</pre>
          </blockquote>
        </div>
      ))}
    </Page>
  );
}
