import {
  checkToken,
  makeErrorResponse,
  makeSuccessResponse,
} from "utils/server.ts";
import { uid } from "usid";
import { define } from "utils/state.ts";
import { del, find, insert, update } from "utils/db.ts";

export const handler = define.handlers({
  async GET(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const id = reqJson.id;
    const tokenUserId = checkToken(req);
    if (id) {
      const post = find(
        "Post",
        tokenUserId ? { id, user_id: tokenUserId } : { id, shared: 1 },
        ["title", "content"],
      );
      if (post.length > 0) {
        return makeSuccessResponse({
          title: post[0]["title"] as string,
          content: post[0]["content"] as string,
        });
      }
    }
    return makeErrorResponse();
  },
  async POST(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const title = reqJson.title || "";
    const content = reqJson.content || "";
    const tokenUserId = checkToken(req);
    if (tokenUserId) {
      const postId = uid(12);
      const post = insert("Post", {
        id: postId,
        title,
        content,
        user_id: tokenUserId,
        shared: 0,
      });
      if (post.length > 0) {
        return makeSuccessResponse(post[0]["id"] as string);
      }
    }
    return makeErrorResponse();
  },
  async PUT(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const id = reqJson.id;
    const title = reqJson.title;
    const content = reqJson.content;
    const tokenUserId = checkToken(req);
    if (tokenUserId && id && (title || content)) {
      const post = find("Post", { id, user_id: tokenUserId });
      if (post.length > 0) {
        const updateObject: { [key: string]: string } = {};
        if (title) updateObject["title"] = title;
        if (content) updateObject["content"] = content;
        const newPost = update("Post", id, updateObject);
        if (newPost.length > 0) {
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
  async DELETE(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const id = reqJson.id;
    const tokenUserId = checkToken(req);
    if (tokenUserId && id) {
      const flag = del("Post", { id, user_id: tokenUserId });
      if (flag) {
        return makeSuccessResponse(true);
      }
    }
    return makeErrorResponse();
  },
});
