import {
  checkToken,
  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 tokenUserId = checkToken(req);
    if (tokenUserId && id) {
      const post = find("Post", { id, user_id: tokenUserId });
      if (post.length > 0) {
        const newPost = update("Post", id, { shared: shared ? 1 : 0 });
        if (newPost.length > 0) {
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
});
