import { Head } from "fresh/runtime";
import { page, type PageProps } from "fresh";
import { checkToken } from "utils/server.ts";
import { find } from "utils/db.ts";
import { define } from "utils/state.ts";
import HomeBar from "../islands/HomeBar.tsx";
import PostList from "../islands/PostList.tsx";
import WelcomeFrame from "../islands/WelcomeFrame.tsx";
import PageContainer from "../components/layout/PageContainer.tsx";

interface HomeProps {
  name: string;
  list: {
    id: string;
    title: string;
    content: string;
    shared: boolean;
    hasPassword: boolean;
  }[];
}

export const handler = define.handlers({
  GET(ctx) {
    const tokenUserId = checkToken(ctx.req);
    if (tokenUserId) {
      const user = find(
        "User",
        { id: tokenUserId },
        ["name"],
      );
      if (user.length > 0) {
        const posts = find("Post", { user_id: tokenUserId }, [
          "id",
          "title",
          "content",
          "shared",
          "share_password",
        ]);
        return page({
          name: user[0]["name"] as string,
          list: posts.map((post) => ({
            id: post["id"] as string,
            title: post["title"] as string,
            content: post["content"] as string,
            shared: post["shared"] === 1,
            hasPassword: Boolean(post["share_password"]),
          })),
        });
      }
    }
    return page({ name: "", list: [] });
  },
});

export default define.page((props: PageProps<HomeProps>) => {
  return (
    <>
      <Head>
        <title>Home</title>
      </Head>
      <PageContainer>
        {props.data.name
          ? (
            <>
              <HomeBar name={props.data.name} />
              <PostList posts={props.data.list} />
            </>
          )
          : <WelcomeFrame />}
      </PageContainer>
    </>
  );
});
