/** @odoo-module **/

// Force-redirect handler for the membership signup flow.
//
// The `cart_update_json` controller override returns
// `{ force_redirect: <signup_url> }` when an anonymous visitor tries to add a
// membership product to the cart in "stay on page" mode
// (`website.add_to_cart_action == 'stay'`), which is the JSON path used by
// `_addToCartInPage` in the core `WebsiteSale` widget. The core handler only
// reads `cart_quantity` / `notification_info` from that response and would
// otherwise ignore `force_redirect`, leaving the membership intercept as a
// silent no-op for the JSON path.
//
// The standard `#add_to_cart` button on the product page posts to
// `/shop/cart/update` (HTTP), handled by `cart_update`, which already raises
// an HTTP redirect — that path is unaffected here.
//
// Why a front-end handler and not an HTTP redirect raised from the controller:
// `_addToCartInPage` calls `rpc("/shop/cart/update_json", ...)` and `rpc` does
// `fetch(...).then(r => r.json())` with the default `redirect: "follow"`. A
// `werkzeug.exceptions.Redirect` (3xx) from the JSON route would be silently
// followed by `fetch`, the `/web/signup` HTML would be parsed as JSON, and the
// frontend would break with an uncaught error. The front-end handler is
// therefore the standard, non-intrusive approach (only acts when
// `data.force_redirect` exists).

import "@website_sale/js/website_sale";
import publicWidget from "@web/legacy/js/public/public_widget";

publicWidget.registry.WebsiteSale.include({
    /**
     * @override
     */
    async _addToCartInPage(params) {
        const data = await this._super.apply(this, arguments);
        if (data && data.force_redirect) {
            window.location.href = data.force_redirect;
        }
        return data;
    },
});