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 method = request.method;

        if (method === 'DELETE') {
            // console.log('🗑️ Delete Conversation API - User:', user, 'ID:', id);

            // 调用服务端API删除会话
            const data = await difyClient.deleteConversation(id, user);

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

            return json(data, {
                headers: {
                    'Set-Cookie': await commitSession(session),
                },
            });
        }

        return json({ error: '不支持的请求方法' }, { status: 405 });
    } catch (error: any) {
        console.error('❌ Delete Conversation API - Error:', error);
        return json(
            {
                error: error.message || '删除会话失败'
            },
            {
                status: 500,
                headers: {
                    'Set-Cookie': await commitSession((await getSessionInfo(request)).session),
                },
            }
        );
    }
} 