import { type ActionFunctionArgs } from '@remix-run/node';
import { API_BASE_URL } from '~/config/api-config';

/**
 * POST /api/dataset/datasets/:datasetId/documents/:documentId/update-by-file
 * 通过文件更新文档（重新处理）
 */
export async function action({ request, params }: ActionFunctionArgs) {
    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        if (!frontendJWT) {
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                { status: 401, headers: { 'Content-Type': 'application/json' } }
            );
        }

        const { datasetId, documentId } = params;
        if (!datasetId || !documentId) {
            return new Response(
                JSON.stringify({ error: '缺少 datasetId 或 documentId 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        // 获取表单数据
        const formData = await request.formData();

        console.log('[API] Update Document By File:', { datasetId, documentId });

        // 转发请求到 FastAPI
        // Dify API: POST /datasets/{dataset_id}/documents/{document_id}/update-by-file
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/update-by-file`;
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${frontendJWT}`,
            },
            body: formData,
        });

        const data = await response.json();

        return new Response(JSON.stringify(data), {
            status: response.status,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('[API] Update Document By File - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to update document by file' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
