"use strict";
const index = require("./index-QSf6WJj0.cjs");
const indexBrowser = require("./index-browser-RtwB1hqI.cjs");
const server = require("@trpc/server");
const membership = require("./membership-QXlFAcD3.cjs");
const user = require("./user-d8lRSBlE.cjs");
const log = index.logger.getSubLogger({ prefix: ["repository/eventType"] });
const hashedLinkSelect = {
  select: {
    id: true,
    link: true,
    expiresAt: true,
    maxUsageCount: true,
    usageCount: true
  }
};
const userSelect = {
  name: true,
  avatarUrl: true,
  username: true,
  id: true,
  timeZone: true
};
function hostsWithSelectedCalendars(hosts) {
  return hosts.map((host) => ({
    ...host,
    user: user.withSelectedCalendars(host.user)
  }));
}
function usersWithSelectedCalendars(users) {
  return users.map((user$1) => user.withSelectedCalendars(user$1));
}
class EventTypeRepository {
  constructor(prismaClient) {
    this.prismaClient = prismaClient;
    this.generateCreateEventTypeData = (eventTypeCreateData) => {
      const {
        userId,
        profileId,
        teamId,
        parentId,
        scheduleId,
        bookingLimits,
        recurringEvent,
        metadata,
        bookingFields,
        durationLimits,
        ...rest
      } = eventTypeCreateData;
      return {
        ...rest,
        ...userId ? { owner: { connect: { id: userId } } } : null,
        ...profileId ? {
          profile: {
            connect: {
              id: profileId
            }
          }
        } : null,
        ...teamId ? { team: { connect: { id: teamId } } } : null,
        ...parentId ? { parent: { connect: { id: parentId } } } : null,
        ...scheduleId ? { schedule: { connect: { id: scheduleId } } } : null,
        ...metadata ? { metadata } : null,
        ...bookingLimits ? {
          bookingLimits
        } : null,
        ...recurringEvent ? {
          recurringEvent
        } : null,
        ...bookingFields ? {
          bookingFields
        } : null,
        ...durationLimits ? {
          durationLimits
        } : null
      };
    };
  }
  async create(data) {
    return await this.prismaClient.eventType.create({
      data: this.generateCreateEventTypeData(data),
      include: {
        calVideoSettings: true
      }
    });
  }
  async createMany(data) {
    return await this.prismaClient.eventType.createMany({
      data: data.map((d) => this.generateCreateEventTypeData(d))
    });
  }
  async findAllByUpId({ upId, userId }, {
    orderBy,
    where = {},
    cursor: cursorId,
    limit
  } = {}) {
    if (!upId)
      return [];
    const lookupTarget = user.ProfileRepository.getLookupTarget(upId);
    const profileId = lookupTarget.type === user.LookupTarget.User ? null : lookupTarget.id;
    const select = {
      ...membership.eventTypeSelect,
      hashedLink: hashedLinkSelect,
      users: { select: userSelect },
      children: {
        include: {
          users: { select: userSelect }
        }
      },
      hosts: {
        include: {
          user: { select: userSelect }
        }
      },
      team: {
        select: {
          id: true,
          members: {
            select: {
              user: {
                select: {
                  timeZone: true
                }
              }
            },
            take: 1
          }
        }
      }
    };
    log.debug(
      "findAllByUpId",
      indexBrowser.safeStringify({
        upId,
        orderBy,
        argumentWhere: where
      })
    );
    const cursor = cursorId ? { id: cursorId } : void 0;
    const take = limit ? limit + 1 : void 0;
    if (!profileId) {
      return await this.prismaClient.eventType.findMany({
        where: {
          userId: lookupTarget.id,
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    }
    const profile = await user.ProfileRepository.findById(profileId);
    if (profile?.movedFromUser) {
      return await this.prismaClient.eventType.findMany({
        where: {
          OR: [
            // Existing events
            {
              userId: profile.movedFromUser.id,
              profileId: null
            },
            // New events
            {
              profileId
            },
            // Fetch children event-types by userId because profileId is wrong
            {
              userId,
              parentId: {
                not: null
              }
            }
          ],
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    } else {
      return await this.prismaClient.eventType.findMany({
        where: {
          OR: [
            {
              profileId
            },
            // Fetch children event-types by userId because profileId is wrong
            {
              userId,
              parentId: {
                not: null
              }
            }
          ],
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    }
  }
  async findAllByUpIdWithMinimalData({ upId, userId }, {
    orderBy,
    where = {},
    cursor: cursorId,
    limit
  } = {}) {
    if (!upId)
      return [];
    const lookupTarget = user.ProfileRepository.getLookupTarget(upId);
    const profileId = lookupTarget.type === user.LookupTarget.User ? null : lookupTarget.id;
    const select = {
      ...membership.eventTypeSelect,
      hashedLink: hashedLinkSelect
    };
    log.debug(
      "findAllByUpIdWithMinimalData",
      indexBrowser.safeStringify({
        upId,
        orderBy,
        argumentWhere: where
      })
    );
    const cursor = cursorId ? { id: cursorId } : void 0;
    const take = limit ? limit + 1 : void 0;
    if (!profileId) {
      return await this.prismaClient.eventType.findMany({
        where: {
          userId: lookupTarget.id,
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    }
    const profile = await user.ProfileRepository.findById(profileId);
    if (profile?.movedFromUser) {
      return await this.prismaClient.eventType.findMany({
        where: {
          OR: [
            // Existing events
            {
              userId: profile.movedFromUser.id,
              profileId: null
            },
            // New events
            {
              profileId
            },
            // Fetch children event-types by userId because profileId is wrong
            {
              userId,
              parentId: {
                not: null
              }
            }
          ],
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    } else {
      return await this.prismaClient.eventType.findMany({
        where: {
          OR: [
            {
              profileId
            },
            // Fetch children event-types by userId because profileId is wrong
            {
              userId,
              parentId: {
                not: null
              }
            }
          ],
          ...where
        },
        select,
        cursor,
        take,
        orderBy
      });
    }
  }
  async findTeamEventTypes({
    teamId,
    parentId,
    userId,
    limit,
    cursor,
    orderBy,
    where = {}
  }) {
    const userSelect2 = {
      name: true,
      avatarUrl: true,
      username: true,
      id: true,
      timeZone: true
    };
    const select = {
      ...membership.eventTypeSelect,
      hashedLink: hashedLinkSelect,
      users: { select: userSelect2, take: 5 },
      children: {
        include: {
          users: { select: userSelect2, take: 5 }
        }
      },
      hosts: {
        include: {
          user: { select: userSelect2 }
        },
        take: 5
      },
      team: {
        select: {
          id: true,
          members: {
            select: {
              user: {
                select: {
                  timeZone: true
                }
              }
            },
            take: 1
          }
        }
      }
    };
    const teamMembership = await this.prismaClient.membership.findFirst({
      where: {
        OR: [
          {
            teamId,
            userId,
            accepted: true
          },
          {
            team: {
              parent: {
                ...parentId ? { id: parentId } : {},
                members: {
                  some: {
                    userId,
                    accepted: true,
                    role: { in: [index.MembershipRole.ADMIN, index.MembershipRole.OWNER] }
                  }
                }
              }
            }
          }
        ]
      }
    });
    if (!teamMembership)
      throw new server.TRPCError({ code: "UNAUTHORIZED" });
    return await index.prisma.eventType.findMany({
      where: {
        teamId,
        ...where
      },
      select,
      cursor: cursor ? { id: cursor } : void 0,
      take: limit ? limit + 1 : void 0,
      // We take +1 as itll be used for the next cursor
      orderBy
    });
  }
  async findAllByUserId({ userId }) {
    return await this.prismaClient.eventType.findMany({
      where: {
        userId
      }
    });
  }
  async findTitleById({ id }) {
    return await this.prismaClient.eventType.findUnique({
      where: {
        id
      },
      select: {
        title: true
      }
    });
  }
  async findByIdWithUserAccess({ id, userId }) {
    return await this.prismaClient.eventType.findUnique({
      where: {
        id,
        OR: [{ userId }, { hosts: { some: { userId } } }, { users: { some: { id: userId } } }]
      }
    });
  }
  async findById({ id, userId }) {
    const userSelect2 = {
      name: true,
      avatarUrl: true,
      username: true,
      id: true,
      email: true,
      locale: true,
      defaultScheduleId: true,
      isPlatformManaged: true,
      timeZone: true
    };
    const CompleteEventTypeSelect = {
      id: true,
      title: true,
      slug: true,
      description: true,
      interfaceLanguage: true,
      length: true,
      isInstantEvent: true,
      instantMeetingExpiryTimeOffsetInSeconds: true,
      instantMeetingParameters: true,
      aiPhoneCallConfig: true,
      offsetStart: true,
      hidden: true,
      locations: true,
      eventName: true,
      customInputs: true,
      timeZone: true,
      periodType: true,
      metadata: true,
      periodDays: true,
      periodStartDate: true,
      periodEndDate: true,
      periodCountCalendarDays: true,
      lockTimeZoneToggleOnBookingPage: true,
      lockedTimeZone: true,
      requiresConfirmation: true,
      requiresConfirmationForFreeEmail: true,
      canSendCalVideoTranscriptionEmails: true,
      requiresConfirmationWillBlockSlot: true,
      requiresBookerEmailVerification: true,
      autoTranslateDescriptionEnabled: true,
      fieldTranslations: {
        select: {
          translatedText: true,
          targetLocale: true,
          field: true
        }
      },
      recurringEvent: true,
      hideCalendarNotes: true,
      hideCalendarEventDetails: true,
      disableGuests: true,
      disableCancelling: true,
      disableRescheduling: true,
      allowReschedulingCancelledBookings: true,
      minimumBookingNotice: true,
      beforeEventBuffer: true,
      afterEventBuffer: true,
      slotInterval: true,
      hashedLink: hashedLinkSelect,
      eventTypeColor: true,
      bookingLimits: true,
      onlyShowFirstAvailableSlot: true,
      durationLimits: true,
      maxActiveBookingsPerBooker: true,
      maxActiveBookingPerBookerOfferReschedule: true,
      assignAllTeamMembers: true,
      allowReschedulingPastBookings: true,
      hideOrganizerEmail: true,
      assignRRMembersUsingSegment: true,
      rrSegmentQueryValue: true,
      isRRWeightsEnabled: true,
      rescheduleWithSameRoundRobinHost: true,
      successRedirectUrl: true,
      forwardParamsSuccessRedirect: true,
      currency: true,
      bookingFields: true,
      useEventTypeDestinationCalendarEmail: true,
      customReplyToEmail: true,
      owner: {
        select: {
          id: true,
          timeZone: true
        }
      },
      parent: {
        select: {
          id: true,
          teamId: true
        }
      },
      teamId: true,
      team: {
        select: {
          id: true,
          name: true,
          slug: true,
          parentId: true,
          rrTimestampBasis: true,
          parent: {
            select: {
              slug: true,
              organizationSettings: {
                select: {
                  lockEventTypeCreationForUsers: true
                }
              }
            }
          },
          members: {
            select: {
              role: true,
              accepted: true,
              user: {
                select: {
                  ...userSelect2,
                  eventTypes: {
                    select: {
                      slug: true
                    }
                  }
                }
              }
            }
          }
        }
      },
      restrictionScheduleId: true,
      useBookerTimezone: true,
      users: {
        select: userSelect2
      },
      schedulingType: true,
      schedule: {
        select: {
          id: true,
          name: true
        }
      },
      instantMeetingSchedule: {
        select: {
          id: true,
          name: true
        }
      },
      restrictionSchedule: {
        select: {
          id: true,
          name: true
        }
      },
      hosts: {
        select: {
          isFixed: true,
          userId: true,
          priority: true,
          weight: true,
          scheduleId: true,
          user: {
            select: {
              timeZone: true
            }
          }
        }
      },
      userId: true,
      price: true,
      children: {
        select: {
          owner: {
            select: {
              avatarUrl: true,
              name: true,
              username: true,
              email: true,
              id: true
            }
          },
          hidden: true,
          slug: true
        }
      },
      destinationCalendar: true,
      seatsPerTimeSlot: true,
      seatsShowAttendees: true,
      seatsShowAvailabilityCount: true,
      webhooks: {
        select: {
          id: true,
          subscriberUrl: true,
          payloadTemplate: true,
          active: true,
          eventTriggers: true,
          secret: true,
          eventTypeId: true
        }
      },
      workflows: {
        include: {
          workflow: {
            select: {
              name: true,
              id: true,
              trigger: true,
              time: true,
              timeUnit: true,
              userId: true,
              teamId: true,
              team: {
                select: {
                  id: true,
                  slug: true,
                  name: true,
                  members: true
                }
              },
              activeOn: {
                select: {
                  eventType: {
                    select: {
                      id: true,
                      title: true,
                      parentId: true,
                      _count: {
                        select: {
                          children: true
                        }
                      }
                    }
                  }
                }
              },
              steps: true
            }
          }
        }
      },
      secondaryEmailId: true,
      maxLeadThreshold: true,
      includeNoShowInRRCalculation: true,
      useEventLevelSelectedCalendars: true,
      calVideoSettings: {
        select: {
          disableRecordingForGuests: true,
          disableRecordingForOrganizer: true,
          enableAutomaticTranscription: true,
          enableAutomaticRecordingForOrganizer: true,
          disableTranscriptionForGuests: true,
          disableTranscriptionForOrganizer: true,
          redirectUrlOnExit: true
        }
      }
    };
    const userTeamIds = await membership.MembershipRepository.findUserTeamIds({ userId });
    return await this.prismaClient.eventType.findFirst({
      where: {
        AND: [
          {
            OR: [
              {
                users: {
                  some: {
                    id: userId
                  }
                }
              },
              {
                AND: [{ teamId: { not: null } }, { teamId: { in: userTeamIds } }]
              },
              {
                userId
              }
            ]
          },
          {
            id
          }
        ]
      },
      select: CompleteEventTypeSelect
    });
  }
  async findByIdForOrgAdmin({ id, organizationId }) {
    const userSelect2 = {
      name: true,
      avatarUrl: true,
      username: true,
      id: true,
      email: true,
      locale: true,
      defaultScheduleId: true,
      isPlatformManaged: true,
      timeZone: true
    };
    const CompleteEventTypeSelect = {
      id: true,
      title: true,
      slug: true,
      description: true,
      interfaceLanguage: true,
      length: true,
      isInstantEvent: true,
      instantMeetingExpiryTimeOffsetInSeconds: true,
      instantMeetingParameters: true,
      aiPhoneCallConfig: true,
      offsetStart: true,
      hidden: true,
      locations: true,
      eventName: true,
      customInputs: true,
      timeZone: true,
      periodType: true,
      metadata: true,
      periodDays: true,
      periodStartDate: true,
      periodEndDate: true,
      periodCountCalendarDays: true,
      lockTimeZoneToggleOnBookingPage: true,
      lockedTimeZone: true,
      requiresConfirmation: true,
      requiresConfirmationForFreeEmail: true,
      canSendCalVideoTranscriptionEmails: true,
      requiresConfirmationWillBlockSlot: true,
      requiresBookerEmailVerification: true,
      autoTranslateDescriptionEnabled: true,
      fieldTranslations: {
        select: {
          translatedText: true,
          targetLocale: true,
          field: true
        }
      },
      recurringEvent: true,
      hideCalendarNotes: true,
      hideCalendarEventDetails: true,
      disableGuests: true,
      disableCancelling: true,
      disableRescheduling: true,
      allowReschedulingCancelledBookings: true,
      minimumBookingNotice: true,
      beforeEventBuffer: true,
      afterEventBuffer: true,
      slotInterval: true,
      hashedLink: hashedLinkSelect,
      eventTypeColor: true,
      bookingLimits: true,
      onlyShowFirstAvailableSlot: true,
      durationLimits: true,
      maxActiveBookingsPerBooker: true,
      maxActiveBookingPerBookerOfferReschedule: true,
      assignAllTeamMembers: true,
      allowReschedulingPastBookings: true,
      hideOrganizerEmail: true,
      assignRRMembersUsingSegment: true,
      rrSegmentQueryValue: true,
      isRRWeightsEnabled: true,
      rescheduleWithSameRoundRobinHost: true,
      successRedirectUrl: true,
      forwardParamsSuccessRedirect: true,
      currency: true,
      bookingFields: true,
      useEventTypeDestinationCalendarEmail: true,
      customReplyToEmail: true,
      owner: {
        select: {
          id: true,
          timeZone: true
        }
      },
      parent: {
        select: {
          id: true,
          teamId: true
        }
      },
      teamId: true,
      team: {
        select: {
          id: true,
          name: true,
          slug: true,
          parentId: true,
          rrTimestampBasis: true,
          parent: {
            select: {
              slug: true,
              organizationSettings: {
                select: {
                  lockEventTypeCreationForUsers: true
                }
              }
            }
          },
          members: {
            select: {
              role: true,
              accepted: true,
              user: {
                select: {
                  ...userSelect2,
                  eventTypes: {
                    select: {
                      slug: true
                    }
                  }
                }
              }
            }
          }
        }
      },
      restrictionScheduleId: true,
      useBookerTimezone: true,
      users: {
        select: userSelect2
      },
      schedulingType: true,
      schedule: {
        select: {
          id: true,
          name: true
        }
      },
      instantMeetingSchedule: {
        select: {
          id: true,
          name: true
        }
      },
      restrictionSchedule: {
        select: {
          id: true,
          name: true
        }
      },
      hosts: {
        select: {
          isFixed: true,
          userId: true,
          priority: true,
          weight: true,
          scheduleId: true,
          user: {
            select: {
              timeZone: true
            }
          }
        }
      },
      userId: true,
      price: true,
      children: {
        select: {
          owner: {
            select: {
              avatarUrl: true,
              name: true,
              username: true,
              email: true,
              id: true
            }
          },
          hidden: true,
          slug: true
        }
      },
      destinationCalendar: true,
      seatsPerTimeSlot: true,
      seatsShowAttendees: true,
      seatsShowAvailabilityCount: true,
      webhooks: {
        select: {
          id: true,
          subscriberUrl: true,
          payloadTemplate: true,
          active: true,
          eventTriggers: true,
          secret: true,
          eventTypeId: true
        }
      },
      workflows: {
        include: {
          workflow: {
            select: {
              name: true,
              id: true,
              trigger: true,
              time: true,
              timeUnit: true,
              userId: true,
              teamId: true,
              team: {
                select: {
                  id: true,
                  slug: true,
                  name: true,
                  members: true
                }
              },
              activeOn: {
                select: {
                  eventType: {
                    select: {
                      id: true,
                      title: true,
                      parentId: true,
                      _count: {
                        select: {
                          children: true
                        }
                      }
                    }
                  }
                }
              },
              steps: true
            }
          }
        }
      },
      secondaryEmailId: true,
      maxLeadThreshold: true,
      includeNoShowInRRCalculation: true,
      useEventLevelSelectedCalendars: true,
      calVideoSettings: {
        select: {
          disableRecordingForGuests: true,
          disableRecordingForOrganizer: true,
          enableAutomaticTranscription: true,
          enableAutomaticRecordingForOrganizer: true,
          disableTranscriptionForGuests: true,
          disableTranscriptionForOrganizer: true,
          redirectUrlOnExit: true
        }
      }
    };
    const orgUserEventTypeQuery = {
      AND: [{ userId: { not: null } }, { owner: { profiles: { some: { organizationId } } } }]
    };
    const orgTeamEventTypeQuery = {
      AND: [{ teamId: { not: null } }, { team: { parentId: organizationId } }]
    };
    return await this.prismaClient.eventType.findFirst({
      where: {
        AND: [
          { id },
          {
            OR: [orgUserEventTypeQuery, orgTeamEventTypeQuery]
          }
        ]
      },
      select: CompleteEventTypeSelect
    });
  }
  async findByIdMinimal({ id }) {
    return await this.prismaClient.eventType.findUnique({
      where: {
        id
      }
    });
  }
  async findFirstEventTypeId({ slug, teamId, userId }) {
    return this.prismaClient.eventType.findFirst({
      where: {
        slug,
        ...teamId ? { teamId } : {},
        ...userId ? { userId } : {}
      },
      select: {
        id: true
      }
    });
  }
  async findByIdIncludeHostsAndTeam({ id }) {
    const eventType = await this.prismaClient.eventType.findUnique({
      where: {
        id
      },
      include: {
        hosts: {
          select: {
            user: {
              select: {
                id: true,
                name: true,
                email: true,
                credentials: {
                  select: index.credentialForCalendarServiceSelect
                },
                selectedCalendars: true
              }
            },
            weight: true,
            priority: true,
            createdAt: true
          }
        },
        team: {
          select: {
            parentId: true,
            rrResetInterval: true,
            rrTimestampBasis: true
          }
        }
      }
    });
    if (!eventType) {
      return eventType;
    }
    return {
      ...eventType,
      hosts: hostsWithSelectedCalendars(eventType.hosts)
    };
  }
  async findAllByTeamIdIncludeManagedEventTypes({ teamId }) {
    return await this.prismaClient.eventType.findMany({
      where: {
        OR: [
          {
            teamId
          },
          {
            parent: {
              teamId
            }
          }
        ]
      }
    });
  }
  async findForSlots({ id }) {
    const eventType = await this.prismaClient.eventType.findUnique({
      where: {
        id
      },
      select: {
        id: true,
        slug: true,
        minimumBookingNotice: true,
        length: true,
        offsetStart: true,
        seatsPerTimeSlot: true,
        timeZone: true,
        slotInterval: true,
        beforeEventBuffer: true,
        afterEventBuffer: true,
        bookingLimits: true,
        durationLimits: true,
        assignAllTeamMembers: true,
        schedulingType: true,
        periodType: true,
        periodStartDate: true,
        periodEndDate: true,
        onlyShowFirstAvailableSlot: true,
        allowReschedulingPastBookings: true,
        hideOrganizerEmail: true,
        periodCountCalendarDays: true,
        rescheduleWithSameRoundRobinHost: true,
        periodDays: true,
        metadata: true,
        assignRRMembersUsingSegment: true,
        rrSegmentQueryValue: true,
        isRRWeightsEnabled: true,
        maxLeadThreshold: true,
        includeNoShowInRRCalculation: true,
        useEventLevelSelectedCalendars: true,
        restrictionScheduleId: true,
        useBookerTimezone: true,
        team: {
          select: {
            id: true,
            bookingLimits: true,
            includeManagedEventsInLimits: true,
            parentId: true,
            rrResetInterval: true,
            rrTimestampBasis: true
          }
        },
        parent: {
          select: {
            team: {
              select: {
                id: true,
                bookingLimits: true,
                includeManagedEventsInLimits: true
              }
            }
          }
        },
        schedule: {
          select: {
            id: true,
            availability: {
              select: {
                date: true,
                startTime: true,
                endTime: true,
                days: true
              }
            },
            timeZone: true
          }
        },
        availability: {
          select: {
            date: true,
            startTime: true,
            endTime: true,
            days: true
          }
        },
        hosts: {
          select: {
            isFixed: true,
            createdAt: true,
            weight: true,
            priority: true,
            user: {
              select: {
                credentials: { select: index.credentialForCalendarServiceSelect },
                ...index.availabilityUserSelect
              }
            },
            schedule: {
              select: {
                availability: {
                  select: {
                    date: true,
                    startTime: true,
                    endTime: true,
                    days: true
                  }
                },
                timeZone: true,
                id: true
              }
            }
          }
        },
        users: {
          select: {
            credentials: { select: index.credentialForCalendarServiceSelect },
            ...index.availabilityUserSelect
          }
        }
      }
    });
    if (!eventType) {
      return eventType;
    }
    return {
      ...eventType,
      hosts: hostsWithSelectedCalendars(eventType.hosts),
      users: usersWithSelectedCalendars(eventType.users),
      metadata: indexBrowser.EventTypeMetaDataSchema.parse(eventType.metadata),
      rrSegmentQueryValue: indexBrowser.rrSegmentQueryValueSchema.parse(eventType.rrSegmentQueryValue)
    };
  }
  static getSelectedCalendarsFromUser({
    user: user2,
    eventTypeId
  }) {
    return user2.allSelectedCalendars.filter((calendar) => calendar.eventTypeId === eventTypeId);
  }
}
exports.EventTypeRepository = EventTypeRepository;
