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

export async function action({ request, params }: ActionFunctionArgs) {
    try {
        const { user, session } = await getSessionInfo(request);
        const { id } = params;

        if (!id) {
            return json({ error: '会话ID不能为空' }, { status: 400 });
        }

        const body = await request.json();
        const { auto_generate, name } = body;

        // console.log('💬 Rename Conversation API - User:', user, 'ID:', id, 'Auto Generate:', auto_generate, 'Name:', name);

        // 调用服务端API重命名会话
        const data = await difyClient.renameConversation(id, name, user, auto_generate);

        // console.log('✅ Rename Conversation API - Success:', data);

        return json(data, {
            headers: {
                'Set-Cookie': await commitSession(session),
            },
        });
    } catch (error: any) {
        console.error('❌ Rename Conversation API - Error:', error);
        return json(
            {
                error: error.message || '重命名会话失败'
            },
            {
                status: 500,
                headers: {
                    'Set-Cookie': await commitSession((await getSessionInfo(request)).session),
                },
            }
        );
    }
} 