import { CreateUserRequest } from "../../src/shared/services/createStripeUser";
import { createAppUser, CreateAppUserResponse } from "../_services";

export const onRequestPost: PagesFunction<PagesEnv> = async ({
  request,
  env,
}) => {
  const user = (await request.json()) as CreateUserRequest;

  /**
   * Create the user in external system
   */
  let userResponse;

  try {
    userResponse = (await createAppUser({
      email: user.email,
      firstName: user.firstName,
      lastName: user.lastName,
      credentials: user.credentials,
      birthdate: "1900/01/01",
      username: user.email,
      affiliateId: user.affiliateId,
    })) as CreateAppUserResponse;
  } catch (error: any) {
    return new Response(
      JSON.stringify({
        status: "error",
        error: error?.message || "Something went wrong",
      }),
      {
        status: 400,
      }
    );
  }

  return new Response(
    JSON.stringify({
      // @ts-ignore
      user: userResponse,
    })
  );
};
