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

/**
 * GET /api/dataset/datasets/:datasetId/documents - 获取文档列表
 */
export async function loader({ request, params }: LoaderFunctionArgs) {
    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 } = params;
        if (!datasetId) {
            return new Response(
                JSON.stringify({ error: '缺少 datasetId 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        // 获取查询参数
        const url = new URL(request.url);
        const page = url.searchParams.get('page') || '1';
        const limit = url.searchParams.get('limit') || '20';
        const keyword = url.searchParams.get('keyword') || '';

        console.log('[API] Documents List:', { datasetId, page, limit, keyword });

        // 构建查询参数
        const queryParams = new URLSearchParams({ page, limit });
        if (keyword) queryParams.append('keyword', keyword);

        // 转发请求到 FastAPI
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents?${queryParams}`;
        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] Documents List - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get documents' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}

/**
 * POST /api/dataset/datasets/:datasetId/documents - 创建文档（上传文件）
 */
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 } = params;
        if (!datasetId) {
            return new Response(
                JSON.stringify({ error: '缺少 datasetId 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

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

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

        // 转发请求到 FastAPI (注意：Dify API是 /document/create-by-file，document是单数)
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/document/create-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] Upload Document - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to upload document' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
