"use strict";
const user = require("./user-xjV81VA_.cjs");
const team = require("./team-a8vvscOr.cjs");
const index = require("./i18n-HHdcQbuJ.cjs");
const log = index.logger.getSubLogger({ prefix: ["lib", "createAProfileForAnExistingUser"] });
const createAProfileForAnExistingUser = async ({
  user: user$1,
  organizationId
}) => {
  const teamRepo = new team.TeamRepository(index.prisma);
  const org = await teamRepo.findById({ id: organizationId });
  if (!org) {
    throw new Error(`Organization with id ${organizationId} not found`);
  }
  const existingProfile = await user.ProfileRepository.findByUserIdAndOrgId({
    userId: user$1.id,
    organizationId
  });
  if (existingProfile) {
    return existingProfile;
  }
  const usernameInOrg = user.getOrgUsernameFromEmail(
    user$1.email,
    org.organizationSettings?.orgAutoAcceptEmail ?? null
  );
  const profile = await user.ProfileRepository.createForExistingUser({
    userId: user$1.id,
    organizationId,
    username: usernameInOrg,
    email: user$1.email,
    movedFromUserId: user$1.id
  });
  const userRepo = new user.UserRepository(index.prisma);
  await userRepo.updateWhereId({
    whereId: user$1.id,
    data: {
      movedToProfileId: profile.id
    }
  });
  log.debug(
    "Created profile for user",
    index.safeStringify({ userId: user$1.id, profileId: profile.id, usernameInOrg, username: user$1.currentUsername })
  );
  const orgSlug = org.slug || org.requestedSlug;
  if (!orgSlug) {
    throw new Error(`Organization with id ${organizationId} doesn't have a slug`);
  }
  const orgUrl = user.getOrgFullOrigin(orgSlug);
  if (org.isPlatform) {
    return profile;
  }
  if (user$1.currentUsername) {
    log.debug(`Creating redirect for user ${user$1.currentUsername} to ${orgUrl}/${usernameInOrg}`);
    await index.prisma.tempOrgRedirect.upsert({
      where: {
        from_type_fromOrgId: {
          from: user$1.currentUsername,
          type: index.RedirectType.User,
          fromOrgId: 0
        }
      },
      update: {
        type: index.RedirectType.User,
        from: user$1.currentUsername,
        fromOrgId: 0,
        toUrl: `${orgUrl}/${usernameInOrg}`
      },
      create: {
        type: index.RedirectType.User,
        from: user$1.currentUsername,
        fromOrgId: 0,
        toUrl: `${orgUrl}/${usernameInOrg}`
      }
    });
  } else {
    log.debug(`Skipping redirect setup as ${user$1.id} doesn't have a username`);
  }
  return profile;
};
exports.createAProfileForAnExistingUser = createAProfileForAnExistingUser;
