import {
  getCryptoString,
  makeErrorResponse,
  makeSuccessResponse,
} from "utils/server.ts";
import { define } from "utils/state.ts";
import { find } from "utils/db.ts";
import { setCookie } from "@std/http";

export const handler = define.handlers({
  async POST(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const id = reqJson.id;
    const password = reqJson.password || "";

    if (id && password) {
      const post = find("Post", { id, shared: 1 }, [
        "share_password",
      ]);
      if (post.length > 0) {
        const storedHash = post[0]["share_password"] as string;
        if (storedHash) {
          const inputHash = await getCryptoString(password, "MD5");
          if (inputHash === storedHash) {
            const token = await getCryptoString(
              id + storedHash,
              "MD5",
            );
            const resp = makeSuccessResponse(true);
            setCookie(resp.headers, {
              name: `pd-share-${id}`,
              value: token,
              path: "/",
            });
            return resp;
          }
        }
      }
    }
    return makeErrorResponse();
  },
});
