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

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

export const handler = define.handlers({
  async POST(ctx) {
    const reqJson = await ctx.req.json();
    if (reqJson.email && reqJson.password) {
      const user = find("User", { email: reqJson.email });
      if (user.length === 0) {
        const newUser = insert("User", {
          name: reqJson.email.split("@")[0],
          email: reqJson.email,
          password: await getCryptoString(reqJson.password, "MD5"),
        });
        if (newUser.length > 0) {
          return makeSuccessResponse(true);
        }
      }
    }
    return makeErrorResponse();
  },
});
