/** @odoo-module **/

import { Store } from "@mail/core/common/store_service";
import { Thread } from "@mail/core/common/thread_model";
import { patch } from "@web/core/utils/patch";

/**
 * Patch Thread to support tier mailbox fetch routes.
 * Must be patched before Store so Thread.insert works correctly.
 */
patch(Thread.prototype, {
    /** @type {number|undefined} */
    tier_mailbox_id: undefined,

    getFetchRoute() {
        if (
            this.model === "mail.box" &&
            typeof this.id === "string" &&
            this.id.startsWith("tier_mailbox_") &&
            this.tier_mailbox_id
        ) {
            return `/mail/tier_mailbox/${this.tier_mailbox_id}/messages`;
        }
        return super.getFetchRoute(...arguments);
    },

    getFetchParams() {
        if (
            this.model === "mail.box" &&
            typeof this.id === "string" &&
            this.id.startsWith("tier_mailbox_")
        ) {
            return {};
        }
        return super.getFetchParams(...arguments);
    },
});

/**
 * Patch Store to load tier mailboxes as Thread objects on startup.
 * Follows the same pattern as inbox/starred/history in store_service_patch.js.
 */
patch(Store.prototype, {
    setup() {
        super.setup(...arguments);
        this.tierMailboxThreads = [];
    },

    onStarted() {
        super.onStarted(...arguments);
        // Load tier mailboxes asynchronously after store is ready
        this._loadTierMailboxes().catch((error) => {
            console.warn("[tier_communications] Failed to load tier mailboxes:", error);
        });
    },

    async _loadTierMailboxes() {
        const mailboxes = await this.env.services.orm.call(
            "tier.mailbox",
            "get_accessible_mailboxes",
            [],
            {}
        );

        this.tierMailboxThreads = (mailboxes || []).map((mailboxData) => {
            const threadRecord = this.Thread.insert({
                id: `tier_mailbox_${mailboxData.id}`,
                model: "mail.box",
                display_name: mailboxData.name,
                counter: 0,
            });
            // Store the real DB id for the fetch route
            threadRecord.tier_mailbox_id = mailboxData.id;
            return threadRecord;
        });
    },
});
