"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index$1 = require("./index-QSf6WJj0.cjs");
const scheduleTrigger = require("./scheduleTrigger-ceRYejNK.cjs");
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const defaultResponder = require("./defaultResponder-ZNP4idbH.cjs");
const z = require("zod");
const _metadata = require("./_metadata-ghnAfZkl.cjs");
async function handler$4(req, res) {
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  const appType = "zapier_automation";
  try {
    const alreadyInstalled = await index$1.prisma.credential.findFirst({
      where: {
        type: appType,
        userId: req.session.user.id
      }
    });
    if (alreadyInstalled) {
      throw new Error("Already installed");
    }
    const installation = await index$1.prisma.credential.create({
      data: {
        type: appType,
        key: {},
        userId: req.session.user.id,
        appId: "zapier"
      }
    });
    if (!installation) {
      throw new Error("Unable to create user credential for zapier");
    }
  } catch (error) {
    if (error instanceof Error) {
      return res.status(500).json({ message: error.message });
    }
    return res.status(500);
  }
  return res.status(200).json({ url: "/apps/zapier/setup" });
}
async function handler$3(req, res) {
  const { account: authorizedAccount, appApiKey: validKey } = await scheduleTrigger.validateAccountOrApiKey(req, [
    "READ_BOOKING"
  ]);
  const bookings = await scheduleTrigger.listBookings(validKey, authorizedAccount);
  if (!bookings) {
    return res.status(500).json({ message: "Unable to get bookings." });
  }
  if (bookings.length === 0) {
    validKey ? validKey.userId : authorizedAccount && !authorizedAccount.isTeam ? authorizedAccount.name : null;
    validKey ? validKey.teamId : authorizedAccount && authorizedAccount.isTeam ? authorizedAccount.name : null;
    return res.status(201).json([]);
  }
  res.status(201).json(bookings);
}
const listBookings = defaultHandler.defaultHandler({
  GET: Promise.resolve({ default: defaultResponder.defaultResponder(handler$3) })
});
const querySchema = z.object({
  apiKey: z.string(),
  id: z.string()
});
async function handler$2(req, res) {
  const { id } = querySchema.parse(req.query);
  const { account, appApiKey } = await scheduleTrigger.validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
  const deleteEventSubscription = await scheduleTrigger.deleteSubscription({
    appApiKey,
    account,
    webhookId: id,
    appId: "zapier"
  });
  if (!deleteEventSubscription) {
    return res.status(500).json({ message: "Could not delete subscription." });
  }
  res.status(204).json({ message: "Subscription is deleted." });
}
const deleteSubscription = defaultHandler.defaultHandler({
  DELETE: Promise.resolve({ default: defaultResponder.defaultResponder(handler$2) })
});
async function handler$1(req, res) {
  const { subscriberUrl, triggerEvent } = req.body;
  const { account, appApiKey } = await scheduleTrigger.validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
  const createAppSubscription = await scheduleTrigger.addSubscription({
    appApiKey,
    account,
    triggerEvent,
    subscriberUrl,
    appId: "zapier"
  });
  if (!createAppSubscription) {
    return res.status(500).json({ message: "Could not create subscription." });
  }
  res.status(200).json(createAppSubscription);
}
const addSubscription = defaultHandler.defaultHandler({
  POST: Promise.resolve({ default: defaultResponder.defaultResponder(handler$1) })
});
async function handler(req, res) {
  const apiKey = req.query.apiKey;
  if (!apiKey) {
    return res.status(401).json({ message: "No API key provided" });
  }
  const validKey = await scheduleTrigger.findValidApiKey(apiKey, "zapier");
  if (!validKey) {
    return res.status(401).json({ message: "API key not valid" });
  }
  if (req.method === "GET") {
    try {
      if (validKey.teamId) {
        const team = await index$1.prisma.team.findFirst({
          where: {
            id: validKey.teamId
          }
        });
        return res.status(201).json({ username: team?.name });
      }
      const user = await index$1.prisma.user.findFirst({
        where: {
          id: validKey.userId
        },
        select: {
          username: true
        }
      });
      return res.status(201).json(user);
    } catch (error) {
      console.error(error);
      return res.status(500).json({ message: "Unable to get User." });
    }
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$4,
  addSubscription,
  deleteSubscription,
  listBookings,
  listOOOEntries: scheduleTrigger.listOOOEntries,
  me: handler
}, Symbol.toStringTag, { value: "Module" }));
exports.metadata = _metadata.metadata;
exports.api = index;
