"use strict";
const httpError = require("./http-error-mkY8Ke7V.cjs");
const index = require("./i18n-Bs8xJzoY.cjs");
const Stripe = require("stripe");
const z = require("zod");
const stripeOAuthTokenSchema = z.z.object({
  access_token: z.z.string().optional(),
  scope: z.z.string().optional(),
  livemode: z.z.boolean().optional(),
  token_type: z.z.literal("bearer").optional(),
  refresh_token: z.z.string().optional(),
  stripe_user_id: z.z.string().optional(),
  stripe_publishable_key: z.z.string().optional()
});
stripeOAuthTokenSchema.extend({
  default_currency: z.z.string()
});
const stripePrivateKey = process.env.STRIPE_PRIVATE_KEY || "";
const stripe = new Stripe(stripePrivateKey, {
  apiVersion: "2020-08-27"
});
async function getStripeCustomerIdFromUserId(userId) {
  const user = await index.prisma.user.findUnique({
    where: {
      id: userId
    },
    select: {
      email: true,
      name: true,
      metadata: true
    }
  });
  if (!user?.email)
    throw new httpError.HttpError({ statusCode: 404, message: "User email not found" });
  const customerId = await getStripeCustomerId(user);
  return customerId;
}
async function getStripeCustomerId(user) {
  let customerId = null;
  if (user?.metadata && typeof user.metadata === "object" && "stripeCustomerId" in user.metadata) {
    customerId = (user?.metadata).stripeCustomerId;
  } else {
    const customersResponse = await stripe.customers.list({
      email: user.email,
      limit: 1
    });
    if (customersResponse.data[0]?.id) {
      customerId = customersResponse.data[0].id;
    } else {
      const customer = await stripe.customers.create({ email: user.email });
      customerId = customer.id;
    }
    await index.prisma.user.update({
      where: {
        email: user.email
      },
      data: {
        metadata: {
          ...user.metadata,
          stripeCustomerId: customerId
        }
      }
    });
  }
  return customerId;
}
async function retrieveOrCreateStripeCustomerByEmail(stripeAccountId, email, phoneNumber) {
  const customer = await stripe.customers.list(
    {
      email,
      limit: 1
    },
    {
      stripeAccount: stripeAccountId
    }
  );
  if (customer.data[0]?.id) {
    return customer.data[0];
  } else {
    const newCustomer = await stripe.customers.create(
      { email, phone: phoneNumber ?? void 0 },
      {
        stripeAccount: stripeAccountId
      }
    );
    return newCustomer;
  }
}
exports.getStripeCustomerIdFromUserId = getStripeCustomerIdFromUserId;
exports.retrieveOrCreateStripeCustomerByEmail = retrieveOrCreateStripeCustomerByEmail;
