import { CreateUserRequest } from "../../src/shared/services/createStripeUser";
import {
  createStripeCustomer,
  createStripeSubscription,
  updateStripeSubscription,
} from "../_stripe";

export const onRequestPost: PagesFunction<PagesEnv> = async ({
  request,
  env,
}) => {
  const user = (await request.json()) as CreateUserRequest;

  /**
   * Create stripe user
   *
   * @return  {Stripe.Customer}  The stripe user
   */
  const customer = await createStripeCustomer(
    {
      email: user.email,
      name: user.firstName + " " + user.lastName,
      metadata: {
        source: "SignupForm",
        priceId: user.priceId, // just for reference
      },
    },
    env.STRIPE_SECRET_KEY
  );
  /**
   * Create the subscription and assign the user
   *
   * @return  {Stripe.Subscription}  The stripe subcription
   */
  const subscription = await createStripeSubscription(
    {
      customer: customer.id,
      items: [
        {
          price: user.priceId,
        },
      ],
      coupon: user.coupon,
      payment_behavior: "default_incomplete",
      expand: ["latest_invoice.payment_intent"],
      automatic_tax: {
        enabled: false,
      },
      cancel_at_period_end: false,
    },
    env.STRIPE_SECRET_KEY
  );

  return new Response(
    JSON.stringify({
      // @ts-ignore
      clientSecret: subscription?.latest_invoice?.payment_intent?.client_secret,
      customerId: customer.id,
      subscriptionId: subscription.id,
    })
  );
};
