import { Handlers, PageProps } from "$fresh/server.ts";
import { Database, Option } from "types";
import Msg from "components/Msg.tsx";
import { get_db_obj } from "db";
import Meta from "components/Meta.tsx";
import { msg_style } from "style";

export const handler: Handlers<Option<Database>> = {
    async GET(_, ctx) {
        const db = await get_db_obj();
        if (db.isNone() || !db.unwrap().messages[ctx.params.message_id]) {
            return ctx.renderNotFound();
        }
        return ctx.render(db);
    },
};

export default function MessagePreview({
    data,
    params,
}: PageProps<Option<Database>>) {
    if (
        data.isSome() &&
        params.message_id &&
        data.unwrap().messages[params.message_id]
    ) {
        const db = data.unwrap();
        const id = params.message_id;
        const msg = db.messages[id];
        return (
            <>
                <Meta
                    title={`freshter log message #${id}`}
                    description={msg.content}
                    after_slash={`m/${id}`}
                    color={`${msg_style(msg, db).color ?? "black"}`}
                ></Meta>
                <Msg message={id} db={db} />
            </>
        );
    }
}
