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

export const handler = define.handlers({
  async POST(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const id = reqJson.id;
    const shared = reqJson.shared;
    const password = reqJson.password || "";
    const tokenUserId = checkToken(req);
    if (tokenUserId && id) {
      const post = find("Post", { id, user_id: tokenUserId });
      if (post.length > 0) {
        const hashedPassword = shared && password
          ? await getCryptoString(password, "MD5")
          : "";
        const newPost = update("Post", id, {
          shared: shared ? 1 : 0,
          share_password: hashedPassword,
        });
        if (newPost.length > 0) {
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
});
