import { Handlers, PageProps } from "$fresh/server.ts";
import { createNote } from "@/db/mod.ts";
import { type ContextState, type Note } from "@/types.ts";

export const handler: Handlers<Note, ContextState> = {
  async POST(request, context) {
    const userId = context.state.user ? context.state.user.id : null;
    const content = (await request.formData()).get("content");
    if (!content) throw "no content provided";
    const note = await createNote({ userId, content: content.toString() });
    if (!note) throw "no note created";
    return await context.render(note);
  },
};

export default function NotesPage({ data: { id } }: PageProps<Note>) {
  return (
    <>
      <h1>You created a note!</h1>
      <a href="/note">Back to notes</a>
      <a href={`/note/${id}`}>View your note</a>
    </>
  );
}
