import { SubcriptionProp } from "../../src/shared/services/updateSubcription";
import { updateStripeCustomer, updateStripeSubscription } from "../_stripe";

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

  const subscription = await updateStripeSubscription(
    {
      default_payment_method: body.payment_method,
    },
    env.STRIPE_SECRET_KEY,
    body.subcriptionId
  );

  const customer = await updateStripeCustomer(
    {
      invoice_settings: {
        default_payment_method: body.payment_method,
      },
      expand: ["sources"],
    },
    env.STRIPE_SECRET_KEY,
    body.customerId
  );

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