/**
 * src/web-chat/owner-thread.ts
 *
 * Single source of truth for "which customer row is the owner's primary
 * dashboard chat thread." Both the reader (/api/chat/recent, polled by the
 * dashboard every 8s) and the writers (cron output, subagent results,
 * daily reports) MUST agree on this — otherwise background messages get
 * written to one thread and read from another, and the owner never sees
 * them. That exact mismatch caused cron output to vanish: the writer drifted
 * to the `system-cron` pseudo-customer (its own last_contact kept bumping to
 * the top) while the reader explicitly excluded `system-cron`.
 */
import { supabase } from '../utils/supabase.js';
const SYSTEM_CRON_PHONE = 'system-cron';
/**
 * Resolve the owner's primary chat thread customer id.
 *
 * Selection order (matches /api/chat/recent):
 *   1. The customer with the most messages, excluding the system-cron
 *      pseudo-customer. This is the dashboard's real conversation thread.
 *   2. Fallback: the most-recent non-cron customer by last_contact.
 *   3. Returns undefined if the tenant has no real customer yet — callers
 *      decide whether to create one.
 */
export async function resolveOwnerPrimaryCustomerId(tenantId) {
    const cronId = await getSystemCronCustomerId(tenantId);
    const { data: counts } = await supabase
        .from('messages')
        .select('customer_id')
        .eq('tenant_id', tenantId)
        .limit(2000);
    if (counts && counts.length > 0) {
        const tally = new Map();
        for (const row of counts) {
            if (!row.customer_id)
                continue;
            if (cronId && row.customer_id === cronId)
                continue;
            tally.set(row.customer_id, (tally.get(row.customer_id) ?? 0) + 1);
        }
        let bestId;
        let bestCount = 0;
        for (const [cid, c] of tally) {
            if (c > bestCount) {
                bestId = cid;
                bestCount = c;
            }
        }
        if (bestId)
            return bestId;
    }
    // Fallback: most-recent non-cron customer.
    const { data } = await supabase
        .from('customers')
        .select('id, phone')
        .eq('tenant_id', tenantId)
        .order('last_contact', { ascending: false })
        .limit(5);
    const list = data ?? [];
    return list.find((c) => c.phone !== SYSTEM_CRON_PHONE)?.id;
}
/** Look up the system-cron pseudo-customer id for a tenant (if it exists). */
export async function getSystemCronCustomerId(tenantId) {
    const { data } = await supabase
        .from('customers')
        .select('id')
        .eq('tenant_id', tenantId)
        .eq('phone', SYSTEM_CRON_PHONE)
        .maybeSingle();
    return data?.id;
}
//# sourceMappingURL=owner-thread.js.map