import { Resource } from "../resource.js";
import { logger } from "../util/logger.js";
import { createStripeClient, handleStripeDeleteError } from "./client.js";
/**
 * Create and manage Stripe customers
 *
 * @example
 * // Create a basic customer
 * const basicCustomer = await Customer("basic-customer", {
 *   email: "john@example.com",
 *   name: "John Doe",
 *   description: "Premium customer",
 *   metadata: {
 *     tier: "premium",
 *     source: "website"
 *   }
 * });
 *
 * @example
 * // Create a customer with full address information
 * const customerWithAddress = await Customer("customer-with-address", {
 *   email: "jane@example.com",
 *   name: "Jane Smith",
 *   phone: "+1-555-123-4567",
 *   address: {
 *     line1: "123 Main St",
 *     line2: "Apt 4B",
 *     city: "San Francisco",
 *     state: "CA",
 *     postalCode: "94105",
 *     country: "US"
 *   },
 *   shipping: {
 *     name: "Jane Smith",
 *     address: {
 *       line1: "456 Oak Ave",
 *       city: "Oakland",
 *       state: "CA",
 *       postalCode: "94612",
 *       country: "US"
 *     }
 *   }
 * });
 *
 * @example
 * // Create a business customer with tax exemption
 * const businessCustomer = await Customer("business-customer", {
 *   email: "billing@acmecorp.com",
 *   name: "Acme Corporation",
 *   description: "Enterprise customer",
 *   taxExempt: "exempt",
 *   invoicePrefix: "ACME",
 *   preferredLocales: ["en"],
 *   metadata: {
 *     type: "business",
 *     industry: "technology",
 *     employees: "500+"
 *   }
 * });
 */
export const Customer = Resource("stripe::Customer", async function (_id, props) {
    const stripe = await createStripeClient({ apiKey: props.apiKey });
    if (this.phase === "delete") {
        try {
            if (this.output?.id) {
                await stripe.customers.del(this.output.id);
            }
        }
        catch (error) {
            handleStripeDeleteError(error, "Customer", this.output?.id);
        }
        return this.destroy();
    }
    try {
        let customer;
        if (this.phase === "update" && this.output?.id) {
            const updateParams = {
                address: props.address
                    ? {
                        city: props.address.city,
                        country: props.address.country,
                        line1: props.address.line1,
                        line2: props.address.line2,
                        postal_code: props.address.postalCode,
                        state: props.address.state,
                    }
                    : undefined,
                balance: props.balance,
                description: props.description,
                email: props.email,
                invoice_prefix: props.invoicePrefix,
                metadata: props.metadata,
                name: props.name,
                next_invoice_sequence: props.nextInvoiceSequence,
                phone: props.phone,
                preferred_locales: props.preferredLocales,
                shipping: props.shipping,
                source: props.source,
                tax_exempt: props.taxExempt,
            };
            if (props.invoiceSettings) {
                updateParams.invoice_settings = {
                    custom_fields: props.invoiceSettings.customFields,
                    default_payment_method: props.invoiceSettings.defaultPaymentMethod,
                    footer: props.invoiceSettings.footer,
                    rendering_options: props.invoiceSettings.renderingOptions
                        ? {
                            amount_tax_display: props.invoiceSettings.renderingOptions.amountTaxDisplay,
                        }
                        : null,
                };
            }
            customer = await stripe.customers.update(this.output.id, updateParams);
        }
        else {
            const createParams = {
                address: props.address
                    ? {
                        city: props.address.city,
                        country: props.address.country,
                        line1: props.address.line1,
                        line2: props.address.line2,
                        postal_code: props.address.postalCode,
                        state: props.address.state,
                    }
                    : undefined,
                balance: props.balance,
                description: props.description,
                email: props.email,
                invoice_prefix: props.invoicePrefix,
                metadata: props.metadata,
                name: props.name,
                next_invoice_sequence: props.nextInvoiceSequence,
                payment_method: props.paymentMethod,
                phone: props.phone,
                preferred_locales: props.preferredLocales,
                shipping: props.shipping,
                source: props.source,
                tax_exempt: props.taxExempt,
                test_clock: props.testClock,
            };
            if (props.invoiceSettings) {
                createParams.invoice_settings = {
                    custom_fields: props.invoiceSettings.customFields,
                    default_payment_method: props.invoiceSettings.defaultPaymentMethod,
                    footer: props.invoiceSettings.footer,
                    rendering_options: props.invoiceSettings.renderingOptions
                        ? {
                            amount_tax_display: props.invoiceSettings.renderingOptions.amountTaxDisplay,
                        }
                        : null,
                };
            }
            if ((props.adopt ?? this.scope.adopt) && props.email) {
                const existingCustomers = await stripe.customers.list({
                    email: props.email,
                    limit: 1,
                });
                if (existingCustomers.data.length > 0) {
                    const existingCustomer = existingCustomers.data[0];
                    const adoptUpdateParams = {
                        address: props.address
                            ? {
                                city: props.address.city,
                                country: props.address.country,
                                line1: props.address.line1,
                                line2: props.address.line2,
                                postal_code: props.address.postalCode,
                                state: props.address.state,
                            }
                            : undefined,
                        balance: props.balance,
                        description: props.description,
                        email: props.email,
                        invoice_prefix: props.invoicePrefix,
                        metadata: props.metadata,
                        name: props.name,
                        next_invoice_sequence: props.nextInvoiceSequence,
                        phone: props.phone,
                        preferred_locales: props.preferredLocales,
                        shipping: props.shipping,
                        source: props.source,
                        tax_exempt: props.taxExempt,
                    };
                    if (props.invoiceSettings) {
                        adoptUpdateParams.invoice_settings = {
                            custom_fields: props.invoiceSettings.customFields,
                            default_payment_method: props.invoiceSettings.defaultPaymentMethod,
                            footer: props.invoiceSettings.footer,
                            rendering_options: props.invoiceSettings.renderingOptions
                                ? {
                                    amount_tax_display: props.invoiceSettings.renderingOptions.amountTaxDisplay,
                                }
                                : null,
                        };
                    }
                    customer = await stripe.customers.update(existingCustomer.id, adoptUpdateParams);
                }
                else {
                    customer = await stripe.customers.create(createParams);
                }
            }
            else {
                customer = await stripe.customers.create(createParams);
            }
        }
        return {
            id: customer.id,
            object: customer.object,
            address: customer.address
                ? {
                    city: customer.address.city || undefined,
                    country: customer.address.country || undefined,
                    line1: customer.address.line1 || undefined,
                    line2: customer.address.line2 || undefined,
                    postalCode: customer.address.postal_code || undefined,
                    state: customer.address.state || undefined,
                }
                : undefined,
            balance: customer.balance || undefined,
            created: customer.created,
            currency: customer.currency || undefined,
            defaultSource: typeof customer.default_source === "string"
                ? customer.default_source
                : undefined,
            delinquent: customer.delinquent || undefined,
            description: customer.description || undefined,
            discount: customer.discount || undefined,
            email: customer.email || undefined,
            invoicePrefix: customer.invoice_prefix || undefined,
            invoiceSettings: customer.invoice_settings
                ? {
                    customFields: customer.invoice_settings.custom_fields?.map((field) => ({
                        name: field.name,
                        value: field.value,
                    })) || undefined,
                    defaultPaymentMethod: typeof customer.invoice_settings.default_payment_method ===
                        "string"
                        ? customer.invoice_settings.default_payment_method
                        : customer.invoice_settings.default_payment_method?.id ||
                            undefined,
                    footer: customer.invoice_settings.footer || undefined,
                    renderingOptions: customer.invoice_settings.rendering_options
                        ? {
                            amountTaxDisplay: customer.invoice_settings
                                .rendering_options.amount_tax_display,
                        }
                        : undefined,
                }
                : undefined,
            livemode: customer.livemode,
            metadata: customer.metadata || undefined,
            name: customer.name || undefined,
            nextInvoiceSequence: customer.next_invoice_sequence || undefined,
            phone: customer.phone || undefined,
            preferredLocales: customer.preferred_locales || undefined,
            shipping: customer.shipping
                ? {
                    address: customer.shipping.address
                        ? {
                            city: customer.shipping.address.city || undefined,
                            country: customer.shipping.address.country || undefined,
                            line1: customer.shipping.address.line1 || undefined,
                            line2: customer.shipping.address.line2 || undefined,
                            postalCode: customer.shipping.address.postal_code || undefined,
                            state: customer.shipping.address.state || undefined,
                        }
                        : undefined,
                    name: customer.shipping.name || undefined,
                    phone: customer.shipping.phone || undefined,
                }
                : undefined,
            sources: customer.sources || undefined,
            subscriptions: customer.subscriptions || undefined,
            taxExempt: customer.tax_exempt || undefined,
            taxIds: customer.tax_ids || undefined,
        };
    }
    catch (error) {
        logger.error("Error creating/updating customer:", error);
        throw error;
    }
});
//# sourceMappingURL=customer.js.map