import { Resource } from "../resource.js";
import { logger } from "../util/logger.js";
import { createStripeClient, handleStripeDeleteError, isStripeConflictError, } from "./client.js";
/**
 * Create and manage Stripe product features
 *
 * @example
 * // Attach an API access feature to a product
 * const productApiFeature = await ProductFeature("product-api-access", {
 *   product: "prod_xyz123",
 *   entitlementFeature: "feat_abc456"
 * });
 *
 * @example
 * // Attach analytics feature to a premium product
 * const productAnalytics = await ProductFeature("premium-analytics", {
 *   product: "prod_premium789",
 *   entitlementFeature: "feat_analytics123"
 * });
 *
 * @example
 * // Attach custom integrations to enterprise product
 * const enterpriseIntegrations = await ProductFeature("enterprise-integrations", {
 *   product: "prod_enterprise456",
 *   entitlementFeature: "feat_integrations789"
 * });
 */
export const ProductFeature = Resource("stripe::ProductFeature", async function (_id, props) {
    const stripe = await createStripeClient({ apiKey: props.apiKey });
    if (this.phase === "delete") {
        try {
            if (this.output?.id && this.output?.product) {
                await stripe.products.deleteFeature(this.output.product, this.output.id);
            }
        }
        catch (error) {
            handleStripeDeleteError(error, "ProductFeature", this.output?.id);
        }
        return this.destroy();
    }
    try {
        let productFeature;
        if (this.phase === "update" && this.output?.id) {
            throw new Error("Product features cannot be updated after creation");
        }
        else {
            try {
                productFeature = await stripe.products.createFeature(props.product, {
                    entitlement_feature: props.entitlementFeature,
                });
            }
            catch (error) {
                if (isStripeConflictError(error) &&
                    (props.adopt ?? this.scope.adopt)) {
                    throw new Error("ProductFeature adoption is not supported - product features cannot be uniquely identified for adoption");
                }
                else {
                    throw error;
                }
            }
        }
        return {
            id: productFeature.id,
            object: productFeature.object,
            product: props.product,
            entitlementFeature: props.entitlementFeature,
            entitlementFeatureObject: productFeature.entitlement_feature || undefined,
            livemode: productFeature.livemode,
        };
    }
    catch (error) {
        logger.error("Error creating product feature:", error);
        throw error;
    }
});
//# sourceMappingURL=product-feature.js.map