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 }: ActionFunctionArgs) {
    try {
        const { user, session } = await getSessionInfo(request);

        // console.log('💬 File Upload API - User:', user);

        // 从请求中获取文件
        const formData = await request.formData();
        const file = formData.get('file') as File;

        if (!file) {
            return json({ error: '没有找到文件' }, { status: 400 });
        }

        // 获取文件内容
        const fileBuffer = await file.arrayBuffer();

        // 这里需要在dify-client.server.ts中添加上传文件的方法
        // 目前我们返回一个临时响应
        // TODO: 实现文件上传功能

        // 构造模拟响应
        const uploadId = `upload_${Date.now()}`;

        // console.log('✅ File Upload API - Success:', { id: uploadId, fileName: file.name, size: file.size });

        return json({ id: uploadId }, {
            headers: {
                'Set-Cookie': await commitSession(session),
            },
        });
    } catch (error: any) {
        console.error('❌ File Upload API - Error:', error);
        return json(
            {
                error: error.message || '文件上传失败'
            },
            {
                status: 500,
                headers: {
                    'Set-Cookie': await commitSession((await getSessionInfo(request)).session),
                },
            }
        );
    }
} 