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

export const handler: Handlers = {
  async POST(req: Request) {
    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][0] as string
        ) {
          // Store new password
          const newUser = update("User", tokenUserId, {
            password: await getCryptoString(reqJson.new, "MD5"),
          });
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
};
