"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const schedule = require("./schedule-an-YFTc3.cjs");
const availability = require("./availability-Az49medN.cjs");
const server = require("@trpc/server");
const updateSchedule = async ({ input, user, prisma }) => {
  const availability$1 = input.schedule ? availability.getAvailabilityFromSchedule(input.schedule) : (input.dateOverrides || []).map((dateOverride) => ({
    startTime: dateOverride.start,
    endTime: dateOverride.end,
    date: dateOverride.start,
    days: []
  }));
  const userSchedule = await prisma.schedule.findUnique({
    where: {
      id: input.scheduleId
    },
    select: {
      userId: true,
      name: true,
      id: true
    }
  });
  if (!userSchedule) {
    throw new server.TRPCError({
      code: "UNAUTHORIZED"
    });
  }
  if (userSchedule?.userId !== user.id) {
    const hasEditPermission = await schedule.hasEditPermissionForUserID({
      ctx: {
        user
      },
      input: { memberId: userSchedule.userId }
    });
    if (!hasEditPermission) {
      throw new server.TRPCError({
        code: "UNAUTHORIZED"
      });
    }
  }
  let updatedUser;
  if (input.isDefault) {
    const setupDefault = await schedule.setupDefaultSchedule(user.id, input.scheduleId, prisma);
    updatedUser = setupDefault;
  }
  if (!input.name) {
    return {
      schedule: userSchedule,
      isDefault: updatedUser ? updatedUser.defaultScheduleId === input.scheduleId : user.defaultScheduleId === input.scheduleId
    };
  }
  const schedule$1 = await prisma.schedule.update({
    where: {
      id: input.scheduleId
    },
    data: {
      timeZone: input.timeZone,
      name: input.name,
      availability: {
        deleteMany: {
          scheduleId: {
            equals: input.scheduleId
          }
        },
        createMany: {
          data: [
            ...availability$1,
            ...(input.dateOverrides || []).map((override) => ({
              date: override.start,
              startTime: override.start,
              endTime: override.end
            }))
          ]
        }
      }
    },
    select: {
      id: true,
      userId: true,
      name: true,
      availability: true,
      timeZone: true,
      eventType: {
        select: {
          id: true,
          eventName: true
        }
      }
    }
  });
  const userAvailability = schedule.transformScheduleToAvailabilityForAtom(schedule$1);
  return {
    schedule: schedule$1,
    availability: userAvailability,
    timeZone: schedule$1.timeZone || user.timeZone,
    isDefault: updatedUser ? updatedUser.defaultScheduleId === schedule$1.id : user.defaultScheduleId === schedule$1.id,
    prevDefaultId: user.defaultScheduleId,
    currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId
  };
};
exports.ScheduleRepository = schedule.ScheduleRepository;
exports.updateSchedule = updateSchedule;
