import { Resource } from "../resource.js";
import { logger } from "../util/logger.js";
import { createStripeClient, handleStripeDeleteError, isStripeConflictError, } from "./client.js";
/**
 * Create and manage Stripe customer portal configurations
 *
 * @example
 * // Create a basic portal configuration
 * const basicPortal = await PortalConfiguration("basic-portal", {
 *   businessProfile: {
 *     headline: "Manage your subscription",
 *     privacyPolicyUrl: "https://example.com/privacy",
 *     termsOfServiceUrl: "https://example.com/terms"
 *   },
 *   features: {
 *     invoiceHistory: { enabled: true },
 *     paymentMethodUpdate: { enabled: true }
 *   }
 * });
 *
 * @example
 * // Create a portal with subscription management
 * const subscriptionPortal = await PortalConfiguration("subscription-portal", {
 *   defaultReturnUrl: "https://example.com/account",
 *   features: {
 *     subscriptionCancel: {
 *       enabled: true,
 *       mode: "at_period_end",
 *       prorationBehavior: "none"
 *     },
 *     subscriptionUpdate: {
 *       enabled: true,
 *       defaultAllowedUpdates: ["price", "quantity"],
 *       prorationBehavior: "create_prorations"
 *     }
 *   }
 * });
 *
 * @example
 * // Create a comprehensive portal configuration
 * const fullPortal = await PortalConfiguration("full-portal", {
 *   businessProfile: {
 *     headline: "Manage your Acme Corp subscription",
 *     privacyPolicyUrl: "https://acme.com/privacy",
 *     termsOfServiceUrl: "https://acme.com/terms"
 *   },
 *   defaultReturnUrl: "https://acme.com/dashboard",
 *   features: {
 *     customerUpdate: {
 *       enabled: true,
 *       allowedUpdates: ["email", "address", "shipping", "phone", "tax_id"]
 *     },
 *     invoiceHistory: { enabled: true },
 *     paymentMethodUpdate: { enabled: true },
 *     subscriptionCancel: {
 *       enabled: true,
 *       mode: "immediately",
 *       cancellationReason: {
 *         enabled: true,
 *         options: ["too_expensive", "missing_features", "switched_service"]
 *       }
 *     }
 *   },
 *   metadata: {
 *     environment: "production",
 *     version: "v2"
 *   }
 * });
 */
export const PortalConfiguration = Resource("stripe::PortalConfiguration", async function (_id, props) {
    const stripe = await createStripeClient({ apiKey: props.apiKey });
    if (this.phase === "delete") {
        try {
            if (this.output?.id) {
                const existingConfig = await stripe.billingPortal.configurations.retrieve(this.output.id);
                if (!existingConfig.is_default) {
                    await stripe.billingPortal.configurations.update(this.output.id, {
                        active: false,
                    });
                }
            }
        }
        catch (error) {
            handleStripeDeleteError(error, "PortalConfiguration", this.output?.id);
        }
        return this.destroy();
    }
    try {
        let configuration;
        if (this.phase === "update" && this.output?.id) {
            const updateParams = {
                business_profile: props.businessProfile
                    ? {
                        headline: props.businessProfile.headline,
                        privacy_policy_url: props.businessProfile.privacyPolicyUrl,
                        terms_of_service_url: props.businessProfile.termsOfServiceUrl,
                    }
                    : undefined,
                default_return_url: props.defaultReturnUrl,
                metadata: props.metadata,
            };
            if (props.features) {
                updateParams.features = {
                    customer_update: props.features.customerUpdate
                        ? {
                            allowed_updates: props.features.customerUpdate.allowedUpdates || [],
                            enabled: props.features.customerUpdate.enabled || false,
                        }
                        : { enabled: false },
                    invoice_history: props.features.invoiceHistory
                        ? {
                            enabled: props.features.invoiceHistory.enabled || false,
                        }
                        : undefined,
                    payment_method_update: props.features.paymentMethodUpdate
                        ? {
                            enabled: props.features.paymentMethodUpdate.enabled || false,
                        }
                        : undefined,
                    subscription_cancel: props.features.subscriptionCancel
                        ? {
                            cancellation_reason: props.features.subscriptionCancel
                                .cancellationReason
                                ? {
                                    enabled: props.features.subscriptionCancel.cancellationReason
                                        .enabled || false,
                                    options: props.features.subscriptionCancel.cancellationReason
                                        .options || [],
                                }
                                : undefined,
                            enabled: props.features.subscriptionCancel.enabled || false,
                            mode: props.features.subscriptionCancel.mode || "immediately",
                            proration_behavior: props.features.subscriptionCancel.prorationBehavior ||
                                "none",
                        }
                        : undefined,
                    subscription_update: props.features.subscriptionUpdate
                        ? {
                            default_allowed_updates: props.features.subscriptionUpdate.defaultAllowedUpdates ||
                                [],
                            enabled: props.features.subscriptionUpdate.enabled || false,
                            products: props.features.subscriptionUpdate.products?.map((p) => ({
                                product: p.product,
                                prices: p.prices || [],
                            })) || [],
                            proration_behavior: props.features.subscriptionUpdate.prorationBehavior ||
                                "none",
                        }
                        : undefined,
                };
            }
            configuration = await stripe.billingPortal.configurations.update(this.output.id, updateParams);
        }
        else {
            const createParams = {
                business_profile: props.businessProfile
                    ? {
                        headline: props.businessProfile.headline,
                        privacy_policy_url: props.businessProfile.privacyPolicyUrl,
                        terms_of_service_url: props.businessProfile.termsOfServiceUrl,
                    }
                    : undefined,
                default_return_url: props.defaultReturnUrl,
                metadata: props.metadata,
                features: {
                    customer_update: { enabled: false },
                    invoice_history: { enabled: true },
                    payment_method_update: { enabled: true },
                    subscription_cancel: { enabled: true },
                    subscription_update: {
                        enabled: false,
                        default_allowed_updates: [],
                        products: [],
                        proration_behavior: "none",
                    },
                },
            };
            if (props.features) {
                createParams.features = {
                    customer_update: props.features.customerUpdate
                        ? {
                            allowed_updates: props.features.customerUpdate.allowedUpdates || [],
                            enabled: props.features.customerUpdate.enabled || false,
                        }
                        : { enabled: false },
                    invoice_history: props.features.invoiceHistory
                        ? {
                            enabled: props.features.invoiceHistory.enabled || false,
                        }
                        : undefined,
                    payment_method_update: props.features.paymentMethodUpdate
                        ? {
                            enabled: props.features.paymentMethodUpdate.enabled || false,
                        }
                        : undefined,
                    subscription_cancel: props.features.subscriptionCancel
                        ? {
                            cancellation_reason: props.features.subscriptionCancel
                                .cancellationReason
                                ? {
                                    enabled: props.features.subscriptionCancel.cancellationReason
                                        .enabled || false,
                                    options: props.features.subscriptionCancel.cancellationReason
                                        .options || [],
                                }
                                : undefined,
                            enabled: props.features.subscriptionCancel.enabled || false,
                            mode: props.features.subscriptionCancel.mode || "immediately",
                            proration_behavior: props.features.subscriptionCancel.prorationBehavior ||
                                "none",
                        }
                        : undefined,
                    subscription_update: props.features.subscriptionUpdate
                        ? {
                            default_allowed_updates: props.features.subscriptionUpdate.defaultAllowedUpdates ||
                                [],
                            enabled: props.features.subscriptionUpdate.enabled || false,
                            products: props.features.subscriptionUpdate.products?.map((p) => ({
                                product: p.product,
                                prices: p.prices || [],
                            })) || [],
                            proration_behavior: props.features.subscriptionUpdate.prorationBehavior ||
                                "none",
                        }
                        : undefined,
                };
            }
            try {
                configuration =
                    await stripe.billingPortal.configurations.create(createParams);
            }
            catch (error) {
                if (isStripeConflictError(error) &&
                    (props.adopt ?? this.scope.adopt)) {
                    throw new Error("PortalConfiguration adoption is not supported - portal configurations cannot be uniquely identified for adoption");
                }
                else {
                    throw error;
                }
            }
        }
        return {
            id: configuration.id,
            object: configuration.object,
            active: configuration.active,
            application: typeof configuration.application === "string"
                ? configuration.application
                : undefined,
            businessProfile: configuration.business_profile
                ? {
                    headline: configuration.business_profile.headline || undefined,
                    privacyPolicyUrl: configuration.business_profile.privacy_policy_url || undefined,
                    termsOfServiceUrl: configuration.business_profile.terms_of_service_url ||
                        undefined,
                }
                : undefined,
            created: configuration.created,
            defaultReturnUrl: configuration.default_return_url || undefined,
            features: {
                customerUpdate: configuration.features.customer_update
                    ? {
                        allowedUpdates: configuration.features.customer_update.allowed_updates ||
                            undefined,
                        enabled: configuration.features.customer_update.enabled || undefined,
                    }
                    : undefined,
                invoiceHistory: configuration.features.invoice_history
                    ? {
                        enabled: configuration.features.invoice_history.enabled || undefined,
                    }
                    : undefined,
                paymentMethodUpdate: configuration.features.payment_method_update
                    ? {
                        enabled: configuration.features.payment_method_update.enabled ||
                            undefined,
                    }
                    : undefined,
                subscriptionCancel: configuration.features.subscription_cancel
                    ? {
                        cancellationReason: configuration.features.subscription_cancel
                            .cancellation_reason
                            ? {
                                enabled: configuration.features.subscription_cancel
                                    .cancellation_reason.enabled || undefined,
                                options: configuration.features.subscription_cancel
                                    .cancellation_reason.options || undefined,
                            }
                            : undefined,
                        enabled: configuration.features.subscription_cancel.enabled ||
                            undefined,
                        mode: configuration.features.subscription_cancel.mode || undefined,
                        prorationBehavior: configuration.features.subscription_cancel
                            .proration_behavior || undefined,
                    }
                    : undefined,
                subscriptionUpdate: configuration.features.subscription_update
                    ? {
                        defaultAllowedUpdates: configuration.features.subscription_update
                            .default_allowed_updates || undefined,
                        enabled: configuration.features.subscription_update.enabled ||
                            undefined,
                        products: configuration.features.subscription_update.products?.map((p) => ({
                            product: p.product,
                            prices: p.prices || undefined,
                        })) || undefined,
                        prorationBehavior: configuration.features.subscription_update
                            .proration_behavior || undefined,
                    }
                    : undefined,
            },
            isDefault: configuration.is_default,
            livemode: configuration.livemode,
            metadata: configuration.metadata || undefined,
            updated: configuration.updated,
        };
    }
    catch (error) {
        logger.error("Error creating/updating portal configuration:", error);
        throw error;
    }
});
//# sourceMappingURL=portal-configuration.js.map