import { p as prisma } from "./orgDomains-eTg-cjth.js";
import { v as validateAccountOrApiKey, l as listBookings$1, d as deleteSubscription$1, a as addSubscription$1, f as findValidApiKey, b as listOOOEntries } from "./scheduleTrigger-djVvWFC3.js";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-0QFUGn0p.js";
import z__default from "zod";
import { m } from "./_metadata-jsSxM6wM.js";
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 prisma.credential.findFirst({
      where: {
        type: appType,
        userId: req.session.user.id
      }
    });
    if (alreadyInstalled) {
      throw new Error("Already installed");
    }
    const installation = await 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 validateAccountOrApiKey(req, [
    "READ_BOOKING"
  ]);
  const bookings = await listBookings$1(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({
  GET: Promise.resolve({ default: defaultResponder(handler$3) })
});
const querySchema = z__default.object({
  apiKey: z__default.string(),
  id: z__default.string()
});
async function handler$2(req, res) {
  const { id } = querySchema.parse(req.query);
  const { account, appApiKey } = await validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
  const deleteEventSubscription = await deleteSubscription$1({
    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({
  DELETE: Promise.resolve({ default: defaultResponder(handler$2) })
});
async function handler$1(req, res) {
  const { subscriberUrl, triggerEvent } = req.body;
  const { account, appApiKey } = await validateAccountOrApiKey(req, ["READ_BOOKING", "READ_PROFILE"]);
  const createAppSubscription = await addSubscription$1({
    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({
  POST: Promise.resolve({ default: 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 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 prisma.team.findFirst({
          where: {
            id: validKey.teamId
          }
        });
        return res.status(201).json({ username: team?.name });
      }
      const user = await 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,
  me: handler
}, Symbol.toStringTag, { value: "Module" }));
export {
  index as api,
  m as metadata
};
