import { Handlers, PageProps } from "$fresh/server.ts";
import { query, type QueryObjectResult } 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;
    console.debug(notes);
    return await context.render(notes);
  },
  async POST(request, context) {
    console.debug({ request, context });
    if (request.headers.get("content-type") != "application/json") {
      throw "content-type must be application/json";
    }
    const body = await request.json();
    console.log({ body });
    if (!("content" in body)) {
      throw "no content field present in body";
    }
    const result = await query(
      "insert into notes (content) values ($1) returning id",
      body.content,
    );
    if (result == null) throw "failed to fetch notes";
    const { rows: [{ id }] } = result as QueryObjectResult<Note>;
    console.debug(id);
  },
};

export default function Page({ data }: PageProps<Note[] | null>) {
  return (
    <div>
      <p>Yo!</p>
      <pre>
        {JSON.stringify(data, null, 2)}
      </pre>
    </div>
  );
}
