import { createDefine } from "fresh";
import {
  checkToken,
  makeErrorResponse,
  makeSuccessResponse,
} from "utils/server.ts";
import { find, update } from "utils/db.ts";

const define = createDefine<Record<never, never>>();

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: Boolean(shared) });
        if (newPost.length > 0) {
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
});
