import { randomBytes } from "crypto";
import { s as slugify, g as getTranslation, a as safeStringify } from "./index-browser-c8sQ7p7S.js";
import { g as getAvailabilityFromSchedule, D as DEFAULT_SCHEDULE } from "./availability-lBLmTiu7.js";
import { l as logger, p as prisma, M as MembershipRole, m as WEBAPP_URL } from "./index-Cw1zbw54.js";
import "./createAProfileForAnExistingUser-LCyLSYXy.js";
import "./sentryWrapper-E-bvLHb0.js";
import "./bookingtimestatusdenormalized-OD3UrSn-.js";
import "./team-9uajEZ51.js";
import { P as ProfileRepository } from "./user-YNqbx2fx.js";
import { TRPCError } from "@trpc/server";
import { t as sendTeamInviteEmail } from "./email-manager-ED8hrFPG.js";
const isEmail = (str) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(str);
logger.getSubLogger({ prefix: ["inviteMember.utils"] });
function checkInputEmailIsValid(email) {
  if (!isEmail(email))
    throw new TRPCError({
      code: "BAD_REQUEST",
      message: `Invite failed because ${email} is not a valid email address`
    });
}
async function createNewUsersConnectToOrgIfExists({
  invitations,
  isOrg,
  teamId,
  parentId,
  autoAcceptEmailDomain,
  orgConnectInfoByUsernameOrEmail,
  isPlatformManaged,
  timeFormat,
  weekStart,
  timeZone,
  language,
  creationSource
}) {
  invitations.forEach((invitation) => checkInputEmailIsValid(invitation.usernameOrEmail));
  const createdUsers = await prisma.$transaction(
    async (tx) => {
      const createdUsers2 = [];
      for (let index = 0; index < invitations.length; index++) {
        const invitation = invitations[index];
        const { orgId, autoAccept } = orgConnectInfoByUsernameOrEmail[invitation.usernameOrEmail];
        const [emailUser, emailDomain] = invitation.usernameOrEmail.split("@");
        const [domainName, TLD] = emailDomain.split(".");
        const orgMemberUsername = emailDomain === autoAcceptEmailDomain ? slugify(emailUser) : slugify(`${emailUser}-${domainName}${isPlatformManaged ? `-${TLD}` : ""}`);
        const regularTeamMemberUsername = null;
        const isBecomingAnOrgMember = parentId || isOrg;
        const defaultAvailability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);
        const t = await getTranslation(language ?? "en", "common");
        const createdUser = await tx.user.create({
          data: {
            username: isBecomingAnOrgMember ? orgMemberUsername : regularTeamMemberUsername,
            email: invitation.usernameOrEmail,
            verified: true,
            invitedTo: teamId,
            isPlatformManaged: !!isPlatformManaged,
            timeFormat,
            weekStart,
            timeZone,
            creationSource,
            organizationId: orgId || null,
            // If the user is invited to a child team, they are automatically added to the parent org
            ...orgId ? {
              profiles: {
                createMany: {
                  data: [
                    {
                      uid: ProfileRepository.generateProfileUid(),
                      username: orgMemberUsername,
                      organizationId: orgId
                    }
                  ]
                }
              }
            } : null,
            teams: {
              create: {
                teamId,
                role: invitation.role,
                accepted: autoAccept
                // If the user is invited to a child team, they are automatically accepted
              }
            },
            ...!isPlatformManaged ? {
              schedules: {
                create: {
                  name: t("default_schedule_name"),
                  availability: {
                    createMany: {
                      data: defaultAvailability.map((schedule) => ({
                        days: schedule.days,
                        startTime: schedule.startTime,
                        endTime: schedule.endTime
                      }))
                    }
                  }
                }
              }
            } : {}
          }
        });
        if (parentId) {
          await tx.membership.create({
            data: {
              createdAt: /* @__PURE__ */ new Date(),
              teamId: parentId,
              userId: createdUser.id,
              role: MembershipRole.MEMBER,
              accepted: autoAccept
            }
          });
        }
        createdUsers2.push(createdUser);
      }
      return createdUsers2;
    },
    { timeout: 1e4 }
  );
  return createdUsers;
}
async function sendSignupToOrganizationEmail({
  usernameOrEmail,
  team,
  translation,
  inviterName,
  teamId,
  isOrg
}) {
  try {
    const token = randomBytes(32).toString("hex");
    await prisma.verificationToken.create({
      data: {
        identifier: usernameOrEmail,
        token,
        expires: new Date((/* @__PURE__ */ new Date()).setHours(168)),
        // +1 week
        team: {
          connect: {
            id: teamId
          }
        }
      }
    });
    await sendTeamInviteEmail({
      language: translation,
      from: inviterName || `${team.name}'s admin`,
      to: usernameOrEmail,
      teamName: team.name,
      joinLink: `${WEBAPP_URL}/signup?token=${token}&callbackUrl=/getting-started`,
      isCalcomMember: false,
      isOrg,
      parentTeamName: team?.parent?.name,
      isAutoJoin: false,
      isExistingUserMovedToOrg: false,
      // For a new user there is no prev and new links.
      prevLink: null,
      newLink: null
    });
  } catch (error) {
    logger.error(
      "Failed to send signup to organization email",
      safeStringify({
        usernameOrEmail,
        orgId: teamId
      }),
      error
    );
  }
}
export {
  createNewUsersConnectToOrgIfExists as c,
  sendSignupToOrganizationEmail as s
};
