/*
 * 用户档案模块：备注简介、导入导出、清空记录与删除会话。
 * 作者: @ccfork
 */
import { apiGet, apiPost } from './api.js';
import { els, setMobileView, state } from './state.js';
import { loadMessages } from './chat.js';
import { loadSessions } from './sessions.js';
import { updateCurrentSessionHeader } from './session-header.js';

export function openProfileModal() {
    if (!state.currentSession) return;
    els.profileIdText.textContent = `ID ${state.currentSession.user_id || state.currentSession.id} · IP ${state.currentSession.ip || '-'}`;
    els.remarkInput.value = state.currentSession.remark || '';
    els.introInput.value = state.currentSession.intro || '';
    els.importFormat.value = 'json';
    els.importContent.value = '';
    els.clearChatSideInput.checked = true;
    els.profileModal.classList.add('active');
}

function closeProfileModal() {
    els.profileModal.classList.remove('active');
}

async function saveProfile() {
    if (!state.currentSessionId) return;
    const data = await apiPost({
        action: 'update_session',
        session_id: state.currentSessionId,
        remark: els.remarkInput.value,
        intro: els.introInput.value
    });
    if (data.success) {
        state.currentSession = data.session;
        updateCurrentSessionHeader();
        closeProfileModal();
        loadSessions();
    }
}

async function exportMessages(format) {
    if (!state.currentSessionId) return;
    const data = await apiGet('export_messages', {
        scope: 'admin',
        format,
        session_id: state.currentSessionId
    });
    if (!data.success) return;
    els.importFormat.value = format;
    els.importContent.value = data.content || '';
    els.importContent.focus();
}

async function importMessages() {
    if (!state.currentSessionId) return;
    const data = await apiPost({
        action: 'import_messages',
        session_id: state.currentSessionId,
        format: els.importFormat.value,
        content: els.importContent.value
    });
    if (data.success) {
        els.importContent.value = '';
        await loadMessages(true);
        await loadSessions();
    } else {
        alert(data.error || '导入失败');
    }
}

async function clearMessages() {
    if (!state.currentSessionId) return;
    const syncChat = els.clearChatSideInput.checked;
    const text = syncChat ? '确定清空这位用户两边的小纸条记录吗？' : '确定只清空后台这边的小纸条记录吗？';
    if (!confirm(text)) return;
    els.clearMessagesBtn.disabled = true;
    const data = await apiPost({
        action: 'clear_messages',
        session_id: state.currentSessionId,
        sync_chat: syncChat
    });
    els.clearMessagesBtn.disabled = false;
    if (!data.success) {
        alert(data.error || '清空失败');
        return;
    }
    state.lastMessageId = Number(data.session?.last_read_id || 0);
    els.adminMessages.innerHTML = '<div class="empty-state">记录已经清空啦～</div>';
    closeProfileModal();
    await loadSessions();
}

async function deleteSession() {
    if (!state.currentSessionId) return;
    if (!confirm('确定删除这个会话和对应结果吗？')) return;
    const deletedId = state.currentSessionId;
    const data = await apiPost({ action: 'delete_session', session_id: deletedId });
    if (!data.success) {
        alert(data.error || '删除失败');
        return;
    }
    state.currentSessionId = null;
    state.currentSession = null;
    state.lastMessageId = 0;
    els.currentTitle.textContent = '选择一个用户';
    els.currentMeta.textContent = '左侧点开后就可以写小纸条';
    els.presenceLine.textContent = '状态会在这里冒泡～';
    els.adminMessages.innerHTML = '<div class="empty-state">会话已经删除啦～</div>';
    closeProfileModal();
    await loadSessions();
    setMobileView('users');
}

export function bindProfileModal() {
    els.currentTitle.addEventListener('click', openProfileModal);
    els.saveProfileBtn.addEventListener('click', saveProfile);
    els.closeProfileBtn.addEventListener('click', closeProfileModal);
    els.profileModal.addEventListener('click', (event) => {
        if (event.target === els.profileModal) closeProfileModal();
    });
    els.exportBtn.addEventListener('click', () => exportMessages(els.importFormat.value || 'json'));
    els.importBtn.addEventListener('click', importMessages);
    els.clearMessagesBtn.addEventListener('click', clearMessages);
    els.deleteSessionBtn.addEventListener('click', deleteSession);
}
