import { Stripe } from "stripe";
import { stringify } from "qs";

const STRIPE_API_URL = "https://api.stripe.com";

export async function getCoupon(id: any, secretKey: string) {
  return getStripe<Stripe.Response<Stripe.Subscription>>(
    `/v1/coupons/${id}`,
    secretKey,
    {
      method: "GET",
    }
  );
}

export async function createPaymentIntent(body: any, secretKey: string) {
  return fetchStripe<Stripe.Response<Stripe.Subscription>>(
    "/v1/payment_intents",
    secretKey,
    body,
    {
      method: "POST",
    }
  );
}

export async function createStripeSubscription(
  body: Stripe.SubscriptionCreateParams,
  secretKey: string
) {
  return fetchStripe<Stripe.Response<Stripe.Subscription>>(
    "/v1/subscriptions",
    secretKey,
    body,
    {
      method: "POST",
    }
  );
}

export async function updateStripeSubscription(
  body: Stripe.SubscriptionUpdateParams,
  secretKey: string,
  subcriptionId: string
) {
  return fetchStripe<Stripe.Response<Stripe.Subscription>>(
    `/v1/subscriptions/${subcriptionId}`,
    secretKey,
    body,
    {
      method: "POST",
    }
  );
}

export async function updateStripeCustomer(
  body: Stripe.CustomerUpdateParams,
  secretKey: string,
  customerId: string
) {
  return fetchStripe<Stripe.Response<Stripe.Customer>>(
    `/v1/customers/${customerId}`,
    secretKey,
    body,
    {
      method: "POST",
    }
  );
}

export async function createStripeCustomer(
  body: Stripe.CustomerCreateParams,
  secretKey: string
) {
  return fetchStripe<Stripe.Response<Stripe.Customer>>(
    "/v1/customers",
    secretKey,
    body,
    {
      method: "POST",
    }
  );
}
export async function fetchPrices(
  body: Stripe.PriceListParams,
  secretKey: string
) {
  return fetchStripe<Stripe.ApiListPromise<Stripe.Price>>(
    "/v1/prices?" + new URLSearchParams(body as any),
    secretKey
  );
}

async function fetchStripe<T>(
  endpoint: string,
  secretKey: string,
  body?: any,
  init: RequestInit = {}
): Promise<T> {
  init = {
    ...init,
    body: body ? stringify(body) : undefined,
    headers: {
      ...init.headers,
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `Bearer ${secretKey}`,
    },
  };
  const url = STRIPE_API_URL + endpoint;
  console.log(url, "url");

  const response = await fetch(url, init);

  if (!response.ok || response.status.toString()[0] !== "2") {
    throw new Error(
      `Stripe API call failed to ${endpoint} (${
        response.status
      }): ${JSON.stringify(await response.json())}`
    );
  }

  return response.json();
}

async function getStripe<T>(
  endpoint: string,
  secretKey: string,
  init: RequestInit = {}
): Promise<T> {
  init = {
    ...init,
    headers: {
      ...init.headers,
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: `Bearer ${secretKey}`,
    },
  };
  const url = STRIPE_API_URL + endpoint;
  console.log(url, "url");

  const response = await fetch(url, init);

  if (!response.ok || response.status.toString()[0] !== "2") {
    throw new Error(
      `Stripe API call failed to ${endpoint} (${
        response.status
      }): ${JSON.stringify(await response.json())}`
    );
  }

  return response.json();
}
