import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { p as prisma } from "./i18n-VAwx2uzJ.js";
import Stripe from "stripe";
import { z } from "zod";
const stripeOAuthTokenSchema = z.object({
  access_token: z.string().optional(),
  scope: z.string().optional(),
  livemode: z.boolean().optional(),
  token_type: z.literal("bearer").optional(),
  refresh_token: z.string().optional(),
  stripe_user_id: z.string().optional(),
  stripe_publishable_key: z.string().optional()
});
stripeOAuthTokenSchema.extend({
  default_currency: 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 prisma.user.findUnique({
    where: {
      id: userId
    },
    select: {
      email: true,
      name: true,
      metadata: true
    }
  });
  if (!user?.email)
    throw new 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 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;
  }
}
export {
  getStripeCustomerIdFromUserId as g,
  retrieveOrCreateStripeCustomerByEmail as r
};
