import { h as hasEditPermissionForUserID, s as setupDefaultSchedule, t as transformScheduleToAvailabilityForAtom } from "./schedule-ok5EMNsC.js";
import { S } from "./schedule-ok5EMNsC.js";
import { g as getAvailabilityFromSchedule } from "./user-QM9GuUuS.js";
import { TRPCError } from "@trpc/server";
import { U } from "./getUserAvailability-GGRT4v6k.js";
const updateSchedule = async ({ input, user, prisma }) => {
  const availability = input.schedule ? 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 TRPCError({
      code: "UNAUTHORIZED"
    });
  }
  if (userSchedule?.userId !== user.id) {
    const hasEditPermission = await hasEditPermissionForUserID({
      ctx: {
        user
      },
      input: { memberId: userSchedule.userId }
    });
    if (!hasEditPermission) {
      throw new TRPCError({
        code: "UNAUTHORIZED"
      });
    }
  }
  let updatedUser;
  if (input.isDefault) {
    const setupDefault = await 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 = await prisma.schedule.update({
    where: {
      id: input.scheduleId
    },
    data: {
      timeZone: input.timeZone,
      name: input.name,
      availability: {
        deleteMany: {
          scheduleId: {
            equals: input.scheduleId
          }
        },
        createMany: {
          data: [
            ...availability,
            ...(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 = transformScheduleToAvailabilityForAtom(schedule);
  return {
    schedule,
    availability: userAvailability,
    timeZone: schedule.timeZone || user.timeZone,
    isDefault: updatedUser ? updatedUser.defaultScheduleId === schedule.id : user.defaultScheduleId === schedule.id,
    prevDefaultId: user.defaultScheduleId,
    currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId
  };
};
export {
  S as ScheduleRepository,
  U as UserAvailabilityService,
  updateSchedule
};
