import { type Ref } from 'vue';
import { useChatStore } from '../store/chat';

export function useHandover(
    wsSend: (payload: any) => void,
    pendingClearRef: Ref<boolean>,
    lastUsage: Ref<any>,
) {
    const chatStore = useChatStore();

    function confirmStartNew() {
        const confirmBubble = [...chatStore.messages].reverse().find(m => m.confirmNew);
        if (confirmBubble) confirmBubble.confirmed = true;
        // Keep messages on new session (only agent switch clears)
        chatStore.resetLocalSession();
        pendingClearRef.value = false;
        lastUsage.value = null;
        wsSend({ type: 'new' });
    }

    function staySession() {
        const confirmBubble = [...chatStore.messages].reverse().find(m => m.confirmNew);
        if (confirmBubble) {
            // Mark as confirmed but don't start new session
            confirmBubble.confirmed = true;
            // Optionally, remove the handover prompt after a delay
            setTimeout(() => {
                const idx = chatStore.messages.findIndex(m => m === confirmBubble);
                if (idx !== -1) chatStore.messages.splice(idx, 1);
            }, 1000);
        }
    }

    function startNew() {
        // Keep messages on new session (only agent switch clears)
        chatStore.resetLocalSession();
        pendingClearRef.value = false;
        lastUsage.value = null;
        wsSend({ type: 'new' });
    }

    function startHandover() {
        wsSend({ type: 'handover_request' });
    }

    return { confirmStartNew, staySession, startNew, startHandover };
}
