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

export const handler: Handlers = {
  async POST(req: Request) {
    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();
  },
};
