import { type ActionFunctionArgs } from '@remix-run/node';
import { difyClient } from '../services/dify-client.server';
import { getSessionInfo } from '../utils/session.server';

export async function action({ request }: ActionFunctionArgs) {
    if (request.method !== 'POST') {
        return new Response('Method not allowed', { status: 405 });
    }

    try {
        const { user } = await getSessionInfo(request);
        const body = await request.json();

        const {
            inputs,
            query,
            files,
            conversation_id: conversationId,
            response_mode: responseMode,
        } = body;

        // ('🚀 Chat Messages API - User:', user, 'Query:', query?.substring(0, 100));

        const response = await difyClient.createChatMessage(
            inputs,
            query,
            user,
            responseMode,
            conversationId,
            files
        );

        // 对于流式响应，直接返回流
        if (responseMode === 'streaming') {
            return new Response(response.body, {
                status: response.status,
                headers: {
                    'Content-Type': 'text/event-stream',
                    'Cache-Control': 'no-cache',
                    'Connection': 'keep-alive',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'POST',
                    'Access-Control-Allow-Headers': 'Content-Type',
                },
            });
        }

        // 对于非流式响应，返回JSON
        return new Response(JSON.stringify(response), {
            status: 200,
            headers: {
                'Content-Type': 'application/json',
            },
        });

    } catch (error: any) {
        // console.error('❌ Chat Messages API - Error:', error);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to send message' }),
            {
                status: 500,
                headers: {
                    'Content-Type': 'application/json',
                },
            }
        );
    }
} 