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

export const handler = define.handlers({
  async POST(ctx) {
    const req = ctx.req;
    const reqJson = await req.json();
    const tokenUserId = checkToken(req);
    if (tokenUserId && reqJson.old && reqJson.new) {
      const user = find("User", { id: tokenUserId }, ["password"]);
      if (user.length > 0) {
        // Match old password
        if (
          await getCryptoString(reqJson.old, "MD5") ===
            user[0]["password"] as string
        ) {
          // Store new password
          update("User", tokenUserId, {
            password: await getCryptoString(reqJson.new, "MD5"),
          });
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
});
