/** @odoo-module **/

import { registry } from "@web/core/registry";
import { session } from "@web/session";
import { rpc } from "@web/core/network/rpc";

const RC_ADAPTER_URL = "https://apps.ringcentral.com/integration/ringcentral-embeddable/latest/adapter.js";

let rcWidgetLoaded = false;

async function loadRcWidget() {
    if (rcWidgetLoaded) return;

    let config;
    try {
        config = await rpc("/ringcentral/widget-config", {});
        console.log("[RC Widget] Config received:", JSON.stringify(config));
    } catch (e) {
        console.error("[RC Widget] Failed to fetch config:", e);
        return;
    }

    if (!config || !config.enabled || !config.client_id) {
        console.warn("[RC Widget] Widget disabled or missing client_id", config);
        return;
    }

    rcWidgetLoaded = true;

    const script = document.createElement("script");
    const params = new URLSearchParams({
        clientId: config.client_id,
        appServer: config.app_server || "https://app.ringcentral.com",
        disableInactiveTabCallEvent: "1",
    });
    console.log("[RC Widget] Loading adapter with params:", params.toString());
    script.src = `${RC_ADAPTER_URL}?${params.toString()}`;
    document.head.appendChild(script);

    window.addEventListener("message", (e) => {
        if (!e.data) return;

        switch (e.data.type) {
            case "rc-login-status-notify":
                window.__rcLoggedIn = e.data.loggedIn;
                break;
            case "rc-active-call-notify":
                window.__rcActiveCall = e.data.call;
                break;
            case "rc-call-end-notify":
                _logCallToOdoo(e.data.call);
                break;
            case "rc-adapter-syncPresence":
                window.__rcPresence = {
                    dndStatus: e.data.dndStatus,
                    userStatus: e.data.userStatus,
                    telephonyStatus: e.data.telephonyStatus,
                };
                window.dispatchEvent(new CustomEvent("rc-presence-changed", {
                    detail: window.__rcPresence,
                }));
                break;
        }
    });
}

async function _logCallToOdoo(call) {
    if (!call) return;
    try {
        await rpc("/web/dataset/call_kw", {
            model: "rc.call.history",
            method: "create",
            args: [{
                rc_session_id: String(call.sessionId || ""),
                direction: (call.direction || "").toLowerCase() === "inbound" ? "inbound" : "outbound",
                from_number: call.from || "",
                to_number: call.to || "",
                duration: call.duration || 0,
                status: call.duration > 0 ? "answered" : "missed",
            }],
            kwargs: {},
        });
    } catch {
        // Silently fail -- cron will catch it
    }
}

registry.category("services").add("rc_phone_widget", {
    start() {
        loadRcWidget();
    },
});
