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

/**
 * GET /api/dataset/datasets/:datasetId/documents/:documentId/upload-file
 * 获取文档上传文件信息
 *
 * Dify API: GET /datasets/{dataset_id}/documents/{document_id}/upload-file
 *
 * 返回示例:
 * {
 *   "id": "file_id",
 *   "name": "file_name",
 *   "size": 1024,
 *   "extension": "txt",
 *   "url": "preview_url",
 *   "download_url": "download_url",
 *   "mime_type": "text/plain",
 *   "created_by": "user_id",
 *   "created_at": 1728734540
 * }
 */
export async function loader({ request, params }: LoaderFunctionArgs) {
    try {
        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' } }
            );
        }

        console.log('[API] Upload File Info:', { datasetId, documentId });

        // 转发请求到 FastAPI -> Dify API
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/upload-file`;
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
        });

        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] Upload File Info - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get upload file info' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
