import { apis } from '@/apis';

export interface ChatParams {
    message: string;
    appId?: string;
    sessionId?: string;
    knowledge_ids?: string[];
    document_ids?: string[];
}

export interface ChatMessage {
    id: string;
    role: 'user' | 'assistant';
    content: string;
    createTime?: string;
}

export interface ChatResponse {
    data: {
        content: string;
        event: 'finish' | 'stream';
    };
}

/**
 * Send chat message to backend
 */
export const sendChatMessage = async (
    params: ChatParams,
    onChunk?: (content: string) => void
): Promise<string> => {
    try {
        const response = await apis.post('/deepseek/api/preChat', {
            message: params.message,
            jkApplicationParams: params.appId ? { appId: params.appId } : undefined,
            request_id: params.sessionId,
            returnType: 'stream',
            knowledge_ids: params.knowledge_ids,
            document_ids: params.document_ids,
        });

        // If streaming, handle chunks
        if (onChunk && response.data) {
            let fullContent = '';
            // Process response based on backend format
            if (typeof response.data === 'string') {
                fullContent = response.data;
            } else if (response.data.content) {
                fullContent = response.data.content;
            }
            return fullContent;
        }

        return response.data?.content || '';
    } catch (error) {
        console.error('Chat API error:', error);
        throw error;
    }
};

/**
 * Get chat history
 */
export const getChatHistory = async (sessionId: string): Promise<ChatMessage[]> => {
    try {
        const response = await apis.get(`/deepseek/api/dialog/detail/${sessionId}`);
        return (response.data || []).map((item: any) => ({
            id: item.did,
            role: item.type === 'user' ? 'user' : 'assistant',
            content: item.content,
            createTime: item.create_time,
        }));
    } catch (error) {
        console.error('Get chat history error:', error);
        return [];
    }
};

/**
 * Create new dialog
 */
export const createDialog = async (appId?: string, topic?: string): Promise<string> => {
    try {
        const response = await apis.post('/deepseek/api/dialog/create', {
            appId,
            dialogName: topic || 'New Chat',
        });
        return response.data?.id || '';
    } catch (error) {
        console.error('Create dialog error:', error);
        return '';
    }
};

/**
 * Update dialog name
 */
export const updateDialogName = async (sessionId: string, name: string): Promise<void> => {
    try {
        await apis.put('/deepseek/api/dialog/update', {
            id: sessionId,
            dialogName: name,
        });
    } catch (error) {
        console.error('Update dialog error:', error);
        throw error;
    }
};

/**
 * Delete dialog
 */
export const deleteDialog = async (sessionId: string): Promise<void> => {
    try {
        await apis.delete(`/deepseek/api/dialog/delete/${sessionId}`);
    } catch (error) {
        console.error('Delete dialog error:', error);
        throw error;
    }
};

/**
 * Get application list
 */
export const getApplicationList = async (params?: {
    pageSize?: number;
    pageNum?: number;
    typeId?: string;
    name?: string;
}): Promise<any[]> => {
    try {
        const response = await apis.post('/deepseek/api/getApplicationList', {
            pageSize: params?.pageSize || 1000,
            pageNum: params?.pageNum || 1,
            userId: 1,
            typeId: params?.typeId,
            name: params?.name,
        });
        return response.data?.rows || [];
    } catch (error) {
        console.error('Get application list error:', error);
        return [];
    }
};

/**
 * Get app types
 */
export const getAppTypes = async (): Promise<any[]> => {
    try {
        const response = await apis.get('/deepseek/api/app_type');
        return response.data || [];
    } catch (error) {
        console.error('Get app types error:', error);
        return [];
    }
};
