/** @odoo-module */

// Immediate console log to verify file is loaded
console.log("==============================================");
console.log("[KDS] pos_kds.js FILE IS LOADING!");
console.log("==============================================");

import { Orderline } from "@point_of_sale/app/store/models";
import { PosStore } from "@point_of_sale/app/store/pos_store";
import { patch } from "@web/core/utils/patch";

console.log("[KDS] Imports successful");

// Patch Orderline model
patch(Orderline.prototype, {
    setup(attr) {
        super.setup(...arguments);
        if (attr && attr.preparation_status) {
            this.preparation_status = attr.preparation_status;
        } else if (!this.preparation_status) {
            this.preparation_status = 'waiting';
        }
    },

    init_from_JSON(json) {
        super.init_from_JSON(...arguments);
        if (json.preparation_status) {
            this.preparation_status = json.preparation_status;
        }
    },

    export_as_JSON() {
        const json = super.export_as_JSON(...arguments);
        json.preparation_status = this.preparation_status;
        return json;
    },

    set_preparation_status(status) {
        this.preparation_status = status;
    },

    get_preparation_status() {
        return this.preparation_status;
    },

    get_preparation_status_label() {
        const labels = {
            'waiting': 'Waiting',
            'preparing': 'Preparing',
            'ready': 'Ready',
            'served': 'Served',
            'cancelled': 'Cancelled'
        };
        return labels[this.preparation_status] || this.preparation_status;
    },

    can_be_merged_with(line) {
        // Prevent merging if the existing line is already being prepared or served
        if (this.preparation_status && this.preparation_status !== 'waiting') {
            return false;
        }
        return super.can_be_merged_with(...arguments);
    }
});

console.log("[KDS] Orderline patched successfully");

// Patch PosStore
patch(PosStore.prototype, {
    async _processData(loadedData) {
        console.log("[KDS] _processData called!");
        await super._processData(...arguments);

        const channel = `pos_config_Channel_${this.config.id}`;
        console.log(`[KDS] Setting up channel: ${channel}`);

        try {
            const busService = this.env.services.bus_service;
            busService.addChannel(channel);
            console.log("[KDS] Channel added successfully");

            busService.addEventListener("notification", (event) => {
                console.log("[KDS] *** NOTIFICATION RECEIVED ***", event);
                const notifications = event.detail || [];

                for (const notif of notifications) {
                    if (notif.type === 'kds_update') {
                        console.log("[KDS] *** KDS UPDATE ***", notif.payload);
                        this._handleKdsUpdate(notif.payload);
                    }
                }
            });

            console.log("[KDS] Listener registered successfully");
        } catch (error) {
            console.error("[KDS] ERROR:", error);
        }
    },

    _handleKdsUpdate(payload) {
        console.log("[KDS] Handling update:", payload);

        try {
            const { order_uid, product_id, status, status_label, line_id, order_id } = payload;
            const orders = this.get_order_list();

            let order = orders.find(o => o.server_id === order_id);
            if (!order) {
                order = orders.find(o => o.name === order_uid || o.pos_reference === order_uid);
            }

            if (order) {
                let line = order.get_orderlines().find(l => l.server_id === line_id);
                if (!line) {
                    line = order.get_orderlines().find(l => l.product.id === product_id);
                }

                if (line) {
                    line.set_preparation_status(status);
                    this.env.services.notification.add(
                        `${line.product.display_name} is ${status_label}`,
                        { title: "Kitchen Update", type: "info" }
                    );
                }
            }
        } catch (error) {
            console.error("[KDS] Error in handler:", error);
        }
    }
});

console.log("[KDS] PosStore patched successfully");
console.log("[KDS] MODULE FULLY LOADED!");
