import { getShopifyPricingPlansUrl } from "./shopify-partner.server";
import { BillingService } from "./billing.server";

export interface CreateSubscriptionParams {
  shopDomain: string;
  planName?: string;
  planKey?: string;
  price?: number;
  returnUrl?: string;
  appHandle?: string;
}

export interface ShopifySubscriptionResult {
  success: boolean;
  confirmationUrl?: string;
  pricingUrl?: string;
  error?: string;
}

/**
 * Returns the official Shopify-hosted pricing/plan-selection page URL.
 * Shopify App Pricing delegates all plan selection and payment authorization to Shopify's hosted page:
 * https://admin.shopify.com/store/:store_handle/charges/:app_handle/pricing_plans
 */
export async function createShopifyAppSubscription({
  shopDomain,
  appHandle,
}: CreateSubscriptionParams): Promise<ShopifySubscriptionResult> {
  const pricingUrl = getShopifyPricingPlansUrl(shopDomain, appHandle);
  return {
    success: true,
    confirmationUrl: pricingUrl,
    pricingUrl,
  };
}

/**
 * Fetches the current verified subscription details for a shop via the centralized BillingService.
 */
export async function getShopifyAppSubscription({
  shopDomain,
}: {
  shopDomain: string;
  subscriptionId?: string;
}) {
  return BillingService.getActiveSubscription(shopDomain);
}

/**
 * Directs merchant to Shopify-hosted plan-selection page to change or cancel their subscription.
 */
export async function cancelShopifyAppSubscription({
  shopDomain,
  appHandle,
}: {
  shopDomain: string;
  subscriptionId?: string;
  appHandle?: string;
}): Promise<{ success: boolean; manageUrl: string }> {
  const manageUrl = getShopifyPricingPlansUrl(shopDomain, appHandle);
  return {
    success: true,
    manageUrl,
  };
}
