import stringify from "qs-stringify";
import z__default, { z } from "zod";
import { p as prisma, m as WEBAPP_URL, n as WEBSITE_URL, l as logger } from "./index-Cw1zbw54.js";
import { g as getParsedAppKeysFromSlug } from "./getParsedAppKeysFromSlug-MNhyH762.js";
import { U as appKeysSchema, V as PREMIUM_MONTHLY_PLAN_PRICE, s as slugify, X as paymentOptionEnum, a as safeStringify, Y as PREMIUM_PLAN_PRODUCT_ID, _ as STRIPE_TEAM_MONTHLY_PRICE_ID, $ as paymentOptions } from "./index-browser-c8sQ7p7S.js";
import { stringify as stringify$1 } from "querystring";
import { g as getInstalledAppPath } from "./getInstalledAppPath-6P3H-VDB.js";
import { c as createOAuthAppCredential } from "./createOAuthAppCredential-UOwy2cXA.js";
import { d as decodeOAuthState } from "./decodeOAuthState-KhwGAxqw.js";
import { s as stripe, g as getStripeCustomerIdFromUserId, S as StripeBillingService, r as retrieveOrCreateStripeCustomerByEmail } from "./stripe-billling-service-Uc3Mjf2b.js";
import { g as getSafeRedirectUrl } from "./getSafeRedirectUrl-hxmyPhEi.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import { d as defaultResponder } from "./defaultResponder-s4VQhYfH.js";
import Stripe from "stripe";
import { v4 } from "uuid";
import { E as ErrorWithCode, a as ErrorCode, g as getErrorFromUnknown } from "./errors-SirEabuV.js";
import "@stripe/stripe-js/pure.js";
import { o as sendAwaitingPaymentEmailAndSMS } from "./email-manager-ED8hrFPG.js";
import { m } from "./_metadata-dh7Zb6iv.js";
const getStripeAppKeys = () => getParsedAppKeysFromSlug("stripe", appKeysSchema);
async function handler$3(req, res) {
  const { client_id } = await getStripeAppKeys();
  if (req.method === "GET") {
    const user = await prisma.user.findUnique({
      where: {
        id: req.session?.user?.id
      },
      select: {
        email: true,
        name: true
      }
    });
    const redirect_uri = encodeURI(`${WEBAPP_URL}/api/integrations/stripepayment/callback`);
    const stripeConnectParams = {
      client_id,
      scope: "read_write",
      response_type: "code",
      stripe_user: {
        email: user?.email,
        first_name: user?.name || void 0,
        /** We need this so E2E don't fail for international users */
        country: process.env.NEXT_PUBLIC_IS_E2E ? "US" : void 0
      },
      redirect_uri,
      state: typeof req.query.state === "string" ? req.query.state : void 0
    };
    const params = z.record(z.any()).parse(stripeConnectParams);
    const query = stringify(params);
    const url = `https://connect.stripe.com/oauth/authorize?${query}`;
    res.status(200).json({ url });
  }
}
function getReturnToValueFromQueryState(req) {
  let returnTo = "";
  try {
    returnTo = JSON.parse(`${req.query.state}`).returnTo;
  } catch (error) {
    console.info("No 'returnTo' in req.query.state");
  }
  return returnTo;
}
async function handler$2(req, res) {
  const { code, error, error_description } = req.query;
  const state = decodeOAuthState(req);
  if (error) {
    if (error === "access_denied") {
      state?.onErrorReturnTo ? res.redirect(state.onErrorReturnTo) : res.redirect("/apps/installed/payment");
    }
    const query = stringify$1({ error, error_description });
    res.redirect(`/apps/installed?${query}`);
    return;
  }
  if (!req.session?.user?.id) {
    return res.status(401).json({ message: "You must be logged in to do this" });
  }
  const response = await stripe.oauth.token({
    grant_type: "authorization_code",
    code: code?.toString()
  });
  const data = { ...response, default_currency: "" };
  if (response["stripe_user_id"]) {
    const account = await stripe.accounts.retrieve(response["stripe_user_id"]);
    data["default_currency"] = account.default_currency;
  }
  await createOAuthAppCredential(
    { appId: "stripe", type: "stripe_payment" },
    data,
    req
  );
  const returnTo = getReturnToValueFromQueryState(req);
  res.redirect(returnTo || getInstalledAppPath({ variant: "payment", slug: "stripe" }));
}
async function handler$1(req, res) {
  if (req.method !== "POST" && req.method !== "GET")
    return res.status(405).json({ message: "Method not allowed" });
  if (!req.session?.user?.id)
    return res.status(401).json({ message: "Not authenticated" });
  const customerId = await getStripeCustomerIdFromUserId(req.session.user.id);
  if (!customerId)
    return res.status(400).json({ message: "CustomerId not found in stripe" });
  let return_url = `${WEBAPP_URL}/settings/billing`;
  if (typeof req.query.returnTo === "string") {
    const safeRedirectUrl = getSafeRedirectUrl(req.query.returnTo);
    if (safeRedirectUrl)
      return_url = safeRedirectUrl;
  }
  const stripeSession = await stripe.billingPortal.sessions.create({
    customer: customerId,
    return_url
  });
  res.redirect(302, stripeSession.url);
}
const getPremiumMonthlyPlanPriceId = () => {
  return PREMIUM_MONTHLY_PLAN_PRICE;
};
async function checkPremiumUsername(_username) {
  const username = slugify(_username);
  const response = await fetch(`${WEBSITE_URL}/api/username`, {
    credentials: "include",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ username }),
    method: "POST",
    mode: "cors"
  });
  const json = await response.json();
  return json;
}
async function handler(req, res) {
  if (req.method === "GET") {
    const userId = req.session?.user.id;
    let { intentUsername = null } = req.query;
    const { callbackUrl } = req.query;
    if (!userId || !intentUsername) {
      res.status(404).end();
      return;
    }
    if (intentUsername && typeof intentUsername === "object") {
      intentUsername = intentUsername[0];
    }
    const customerId = await getStripeCustomerIdFromUserId(userId);
    if (!customerId) {
      res.status(404).json({ message: "Missing customer id" });
      return;
    }
    const userData = await prisma.user.findFirst({
      where: { id: userId },
      select: { id: true, metadata: true }
    });
    if (!userData) {
      res.status(404).json({ message: "Missing user data" });
      return;
    }
    const return_url = `${WEBAPP_URL}/api/integrations/stripepayment/paymentCallback?checkoutSessionId={CHECKOUT_SESSION_ID}&callbackUrl=${callbackUrl}`;
    const createSessionParams = {
      mode: "subscription",
      line_items: [
        {
          quantity: 1,
          price: getPremiumMonthlyPlanPriceId()
        }
      ],
      allow_promotion_codes: true,
      customer: customerId,
      success_url: return_url,
      cancel_url: return_url
    };
    const checkPremiumResult = await checkPremiumUsername(intentUsername);
    if (!checkPremiumResult.available) {
      return res.status(404).json({ message: "Intent username not available" });
    }
    const stripeCustomer = await stripe.customers.retrieve(customerId);
    if (!stripeCustomer || stripeCustomer.deleted) {
      return res.status(400).json({ message: "Stripe customer not found or deleted" });
    }
    await stripe.customers.update(customerId, {
      metadata: {
        ...stripeCustomer.metadata,
        username: intentUsername
      }
    });
    if (userData) {
      await prisma.user.update({
        where: { id: userId },
        data: {
          metadata: {
            ...userData.metadata || {},
            isPremium: false
          }
        }
      });
    }
    const checkoutSession = await stripe.checkout.sessions.create(createSessionParams);
    if (checkoutSession && checkoutSession.url) {
      return res.redirect(checkoutSession.url).end();
    }
    return res.status(404).json({ message: "Couldn't redirect to stripe checkout session" });
  }
}
async function getCustomerAndCheckoutSession(checkoutSessionId) {
  const billingService = new StripeBillingService();
  const checkoutSession = await billingService.getCheckoutSession(checkoutSessionId);
  const customerOrCustomerId = checkoutSession.customer;
  let customerId = null;
  if (!customerOrCustomerId) {
    return { checkoutSession, stripeCustomer: null };
  }
  if (typeof customerOrCustomerId === "string") {
    customerId = customerOrCustomerId;
  } else if (customerOrCustomerId.deleted) {
    return { checkoutSession, stripeCustomer: null };
  } else {
    customerId = customerOrCustomerId.id;
  }
  const stripeCustomer = await billingService.getCustomer(customerId);
  if (stripeCustomer.deleted) {
    return { checkoutSession, stripeCustomer: null };
  }
  return { stripeCustomer, checkoutSession };
}
const querySchema = z__default.object({
  callbackUrl: z__default.string().transform((url) => {
    if (url.search(/^https?:\/\//) === -1) {
      url = `${WEBAPP_URL}${url}`;
    }
    return new URL(url);
  }),
  checkoutSessionId: z__default.string()
});
async function getHandler(req, res) {
  const { callbackUrl, checkoutSessionId } = querySchema.parse(req.query);
  const { stripeCustomer, checkoutSession } = await getCustomerAndCheckoutSession(checkoutSessionId);
  if (!stripeCustomer)
    throw new HttpError({
      statusCode: 404,
      message: "Stripe customer not found or deleted",
      url: req.url,
      method: req.method
    });
  let user = await prisma.user.findFirst({
    where: {
      metadata: {
        path: ["stripeCustomerId"],
        equals: stripeCustomer.id
      }
    }
  });
  if (!user && stripeCustomer.email) {
    user = await prisma.user.findFirst({
      where: {
        email: stripeCustomer.email
      }
    });
  }
  if (!user)
    throw new HttpError({ statusCode: 404, message: "User not found", url: req.url, method: req.method });
  if (checkoutSession.payment_status === "paid" && stripeCustomer.metadata.username) {
    try {
      await prisma.user.update({
        data: {
          username: stripeCustomer.metadata.username,
          metadata: {
            ...user.metadata,
            isPremium: true
          }
        },
        where: {
          id: user.id
        }
      });
    } catch (error) {
      console.error(error);
      throw new HttpError({
        statusCode: 400,
        url: req.url,
        method: req.method,
        message: "We have received your payment. Your premium username could still not be reserved. Please contact support@cal.com and mention your premium username"
      });
    }
  }
  callbackUrl.searchParams.set("paymentStatus", checkoutSession.payment_status);
  return res.redirect(callbackUrl.toString()).end();
}
const paymentCallback = defaultHandler({
  GET: Promise.resolve({ default: defaultResponder(getHandler) })
});
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add: handler$3,
  callback: handler$2,
  paymentCallback,
  portal: handler$1,
  subscription: handler
}, Symbol.toStringTag, { value: "Module" }));
function createPaymentLink(opts) {
  const { paymentUid, name, email, date, absolute = true } = opts;
  let link = "";
  if (absolute)
    link = WEBSITE_URL;
  const query = stringify$1({ date, name, email });
  return `${link}/payment/${paymentUid}?${query}`;
}
process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY || "";
const log = logger.getSubLogger({ prefix: ["payment-service:stripe"] });
const stripeCredentialKeysSchema = z__default.object({
  stripe_user_id: z__default.string(),
  default_currency: z__default.string(),
  stripe_publishable_key: z__default.string()
});
const stripeAppKeysSchema = z__default.object({
  client_id: z__default.string(),
  payment_fee_fixed: z__default.number(),
  payment_fee_percentage: z__default.number()
});
class PaymentService {
  constructor(credentials) {
    const keyParsing = stripeCredentialKeysSchema.safeParse(credentials.key);
    if (keyParsing.success) {
      this.credentials = keyParsing.data;
    } else {
      this.credentials = null;
    }
    this.stripe = new Stripe(process.env.STRIPE_PRIVATE_KEY || "", {
      apiVersion: "2020-08-27"
    });
  }
  async getPayment(where) {
    const payment = await prisma.payment.findFirst({ where });
    if (!payment)
      throw new Error("Payment not found");
    if (!payment.externalId)
      throw new Error("Payment externalId not found");
    return { ...payment, externalId: payment.externalId };
  }
  /* This method is for creating charges at the time of booking */
  async create(payment, bookingId, userId, username, bookerName, paymentOption, bookerEmail, bookerPhoneNumber, eventTitle, bookingTitle) {
    try {
      if (paymentOptionEnum.parse(paymentOption) !== "ON_BOOKING") {
        throw new Error("Payment option is not compatible with create method");
      }
      if (!this.credentials) {
        throw new Error("Stripe credentials not found");
      }
      const customer = await retrieveOrCreateStripeCustomerByEmail(
        this.credentials.stripe_user_id,
        bookerEmail,
        bookerPhoneNumber
      );
      const params = {
        amount: payment.amount,
        currency: payment.currency,
        customer: customer.id,
        automatic_payment_methods: {
          enabled: true
        },
        metadata: {
          identifier: "cal.com",
          bookingId,
          calAccountId: userId,
          calUsername: username,
          bookerName,
          bookerEmail,
          bookerPhoneNumber: bookerPhoneNumber ?? null,
          eventTitle: eventTitle || "",
          bookingTitle: bookingTitle || ""
        }
      };
      const paymentIntent = await this.stripe.paymentIntents.create(params, {
        stripeAccount: this.credentials.stripe_user_id
      });
      const paymentData = await prisma.payment.create({
        data: {
          uid: v4(),
          app: {
            connect: {
              slug: "stripe"
            }
          },
          booking: {
            connect: {
              id: bookingId
            }
          },
          amount: payment.amount,
          currency: payment.currency,
          externalId: paymentIntent.id,
          data: Object.assign({}, paymentIntent, {
            stripe_publishable_key: this.credentials.stripe_publishable_key,
            stripeAccount: this.credentials.stripe_user_id
          }),
          fee: 0,
          refunded: false,
          success: false,
          paymentOption: paymentOption || "ON_BOOKING"
        }
      });
      if (!paymentData) {
        throw new Error();
      }
      return paymentData;
    } catch (error) {
      log.error("Stripe: Payment could not be created", bookingId, safeStringify(error));
      throw new Error("payment_not_created_error");
    }
  }
  async collectCard(payment, bookingId, paymentOption, bookerEmail, bookerPhoneNumber) {
    try {
      if (!this.credentials) {
        throw new Error("Stripe credentials not found");
      }
      if (paymentOptionEnum.parse(paymentOption) !== "HOLD") {
        throw new Error("Payment option is not compatible with create method");
      }
      const customer = await retrieveOrCreateStripeCustomerByEmail(
        this.credentials.stripe_user_id,
        bookerEmail,
        bookerPhoneNumber
      );
      const params = {
        customer: customer.id,
        payment_method_types: ["card"],
        metadata: {
          bookingId,
          bookerPhoneNumber: bookerPhoneNumber ?? null
        }
      };
      const setupIntent = await this.stripe.setupIntents.create(params, {
        stripeAccount: this.credentials.stripe_user_id
      });
      const paymentData = await prisma.payment.create({
        data: {
          uid: v4(),
          app: {
            connect: {
              slug: "stripe"
            }
          },
          booking: {
            connect: {
              id: bookingId
            }
          },
          amount: payment.amount,
          currency: payment.currency,
          externalId: setupIntent.id,
          data: Object.assign(
            {},
            {
              setupIntent,
              stripe_publishable_key: this.credentials.stripe_publishable_key,
              stripeAccount: this.credentials.stripe_user_id
            }
          ),
          fee: 0,
          refunded: false,
          success: false,
          paymentOption: paymentOption || "ON_BOOKING"
        }
      });
      return paymentData;
    } catch (error) {
      log.error(
        "Stripe: Payment method could not be collected for bookingId",
        bookingId,
        safeStringify(error)
      );
      throw new Error("Stripe: Payment method could not be collected");
    }
  }
  async chargeCard(payment, _bookingId) {
    try {
      if (!this.credentials) {
        throw new Error("Stripe credentials not found");
      }
      const stripeAppKeys = await prisma.app.findFirst({
        select: {
          keys: true
        },
        where: {
          slug: "stripe"
        }
      });
      const paymentObject = payment.data;
      const setupIntent = paymentObject.setupIntent;
      const { payment_fee_fixed, payment_fee_percentage } = stripeAppKeysSchema.parse(stripeAppKeys?.keys);
      const paymentFee = Math.round(payment.amount * payment_fee_percentage + payment_fee_fixed);
      const customer = await this.stripe.customers.retrieve(setupIntent.customer, {
        stripeAccount: this.credentials.stripe_user_id
      });
      const paymentMethod = await this.stripe.paymentMethods.retrieve(setupIntent.payment_method, {
        stripeAccount: this.credentials.stripe_user_id
      });
      if (!customer) {
        throw new Error(`Stripe customer does not exist for setupIntent ${setupIntent.id}`);
      }
      if (!paymentMethod) {
        throw new Error(`Stripe paymentMethod does not exist for setupIntent ${setupIntent.id}`);
      }
      const params = {
        amount: payment.amount,
        currency: payment.currency,
        application_fee_amount: paymentFee,
        customer: setupIntent.customer,
        payment_method: setupIntent.payment_method,
        off_session: true,
        confirm: true
      };
      const paymentIntent = await this.stripe.paymentIntents.create(params, {
        stripeAccount: this.credentials.stripe_user_id
      });
      const paymentData = await prisma.payment.update({
        where: {
          id: payment.id
        },
        data: {
          success: true,
          data: {
            ...paymentObject,
            paymentIntent
          }
        }
      });
      if (!paymentData) {
        throw new Error();
      }
      return paymentData;
    } catch (error) {
      log.error("Stripe: Could not charge card for payment", _bookingId, safeStringify(error));
      const errorMappings = {
        "your card was declined": "your_card_was_declined",
        "your card does not support this type of purchase": "your_card_does_not_support_this_type_of_purchase",
        "amount must convert to at least": "amount_must_convert_to_at_least"
      };
      let userMessage = "could_not_charge_card";
      if (error instanceof Error) {
        const errorMessage = error.message.toLowerCase();
        for (const [key, message] of Object.entries(errorMappings)) {
          if (errorMessage.includes(key)) {
            userMessage = message;
            break;
          }
        }
      }
      throw new ErrorWithCode(ErrorCode.ChargeCardFailure, userMessage);
    }
  }
  async update() {
    throw new Error("Method not implemented.");
  }
  async refund(paymentId) {
    try {
      const payment = await this.getPayment({
        id: paymentId,
        success: true,
        refunded: false
      });
      const refund = await this.stripe.refunds.create(
        {
          payment_intent: payment.externalId
        },
        { stripeAccount: payment.data["stripeAccount"] }
      );
      if (!refund || refund.status === "failed") {
        throw new Error("Refund failed");
      }
      const updatedPayment = await prisma.payment.update({
        where: {
          id: payment.id
        },
        data: {
          refunded: true
        }
      });
      return updatedPayment;
    } catch (e) {
      const err = getErrorFromUnknown(e);
      throw err;
    }
  }
  async afterPayment(event, booking, paymentData, eventTypeMetadata) {
    await sendAwaitingPaymentEmailAndSMS(
      {
        ...event,
        paymentInfo: {
          link: createPaymentLink({
            paymentUid: paymentData.uid,
            name: booking.user?.name,
            email: booking.user?.email,
            date: booking.startTime.toISOString()
          }),
          paymentOption: paymentData.paymentOption || "ON_BOOKING",
          amount: paymentData.amount,
          currency: paymentData.currency
        }
      },
      eventTypeMetadata
    );
  }
  async deletePayment(paymentId) {
    try {
      const payment = await this.getPayment({
        id: paymentId
      });
      const stripeAccount = payment.data.stripeAccount;
      if (!stripeAccount) {
        throw new Error("Stripe account not found");
      }
      const sessions = await this.stripe.checkout.sessions.list(
        {
          payment_intent: payment.externalId
        },
        { stripeAccount }
      );
      for (const session of sessions.data) {
        await this.stripe.checkout.sessions.expire(session.id, { stripeAccount });
      }
      await this.stripe.paymentIntents.cancel(payment.externalId, { stripeAccount });
      return true;
    } catch (e) {
      log.error("Stripe: Unable to delete Payment in stripe of paymentId", paymentId, safeStringify(e));
      return false;
    }
  }
  getPaymentPaidStatus() {
    throw new Error("Method not implemented.");
  }
  getPaymentDetails() {
    throw new Error("Method not implemented.");
  }
  isSetupAlready() {
    return !!this.credentials;
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  PREMIUM_MONTHLY_PLAN_PRICE,
  PREMIUM_PLAN_PRODUCT_ID,
  PaymentService,
  STRIPE_TEAM_MONTHLY_PRICE_ID,
  paymentOptions,
  stripeCredentialKeysSchema
}, Symbol.toStringTag, { value: "Module" }));
export {
  index$1 as api,
  index as lib,
  m as metadata
};
