// src/routes/api/login.ts
import type { APIContext } from "astro";
import { hashPassword, newUser } from "@utils/auths";

export async function POST({ request, cookies }: APIContext) {
  const formData = await request.formData();

  const email = formData.get("email");
  const firstName = formData.get("first_name");
  const lastName = formData.get("last_name");
  if (
    typeof email !== "string" ||
    typeof lastName !== "string" ||
    typeof firstName !== "string"
  ) {
    return new Response(
      JSON.stringify({
        message: "Text Inputs Only",
      }),
      {
        status: 400,
      }
    );
  }
  try {
    // checks for email + name combinaison
    const password = await hashPassword(
      firstName.trim().split(" ")[0].toLowerCase()
    );

    await newUser({
      lastName,
      firstName,
      email,
      password,
    });

    // return a successful response
    return new Response(
      JSON.stringify({
        message: "Account Created!",
      }),
      {
        status: 201,
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({
        message: error?.message,
      }),
      {
        status: 500,
      }
    );
  }
}
