export async function POST()

in src/app/api/v1/user/welcome-scan/create/route.ts [48:158]


export async function POST(
  req: NextRequest,
): Promise<NextResponse<WelcomeScanBody> | NextResponse<unknown>> {
  const session = await getServerSession();

  if (!session?.user?.subscriber) {
    throw new Error("No fxa_uid found in session");
  }

  const eligible = await isEligibleForFreeScan(
    session.user,
    getCountryCode(await headers()),
  );
  if (!eligible) {
    logger.warn("scan_created_warn", {
      message: "User is not eligible for feature",
    });
    return NextResponse.json({ success: false }, { status: 422 });
  }

  const params: UserInfo = await req.json();
  const requiredParamKeys: Array<keyof UserInfo> = [
    "firstName",
    "lastName",
    "city",
    "state",
    "dateOfBirth",
  ];
  requiredParamKeys.forEach((requiredParamKey) => {
    if (!params[requiredParamKey]) {
      throw new Error(`${requiredParamKey} is required`);
    }
  });

  const {
    firstName,
    middleName,
    lastName,
    nameSuffix,
    city,
    state,
    dateOfBirth,
  } = params;
  if (!meetsAgeRequirement(dateOfBirth)) {
    throw new Error(`User does not meet the age requirement: ${dateOfBirth}`);
  }

  const experimentationId = await getExperimentationId(session.user);
  const experimentData = await getExperiments({
    experimentationId,
    countryCode: getCountryCode(await headers()),
    locale: getLocale(getL10n(await getAcceptLangHeaderInServerComponents())),
  });
  const optionalInfoExperimentData =
    experimentData["Features"]["welcome-scan-optional-info"];

  const profileData: CreateProfileRequest = {
    first_name: firstName,
    last_name: lastName,
    addresses: [{ city, state }],
    birth_date: dateOfBirth,
    ...(optionalInfoExperimentData.enabled &&
      (optionalInfoExperimentData.variant === "middleName" ||
        optionalInfoExperimentData.variant === "suffixAndMiddleName") && {
        middle_name: middleName,
      }),
    ...(optionalInfoExperimentData.enabled &&
      (optionalInfoExperimentData.variant === "suffix" ||
        optionalInfoExperimentData.variant === "suffixAndMiddleName") && {
        name_suffix: nameSuffix,
      }),
  };

  if (typeof session?.user?.subscriber.fxa_uid === "string") {
    try {
      const subscriber = await getSubscriberByFxaUid(
        session.user.subscriber.fxa_uid,
      );

      if (!subscriber) {
        throw new Error("No subscriber found for current session.");
      }
      if (!subscriber.onerep_profile_id) {
        // Create OneRep profile
        const profileId = await createProfile(profileData);
        await setOnerepProfileId(subscriber, profileId);
        await setProfileDetails(profileId, profileData);

        // Start exposure scan
        const scan = await createScan(profileId);
        const scanId = scan.id;
        await setOnerepScan(profileId, scanId, scan.status, "manual");
        // TODO MNTOR-2686 - refactor onerep.ts and centralize logging.
        logger.info("scan_created", {
          onerepScanId: scanId,
          onerepScanStatus: scan.status,
          onerepScanReason: "manual",
        });

        return NextResponse.json({ success: true }, { status: 200 });
      }

      return NextResponse.json({ success: true }, { status: 200 });
    } catch (e) {
      logger.error(e);
      return NextResponse.json({ success: false }, { status: 500 });
    }
  } else {
    return NextResponse.json({ success: false }, { status: 401 });
  }
}