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

/**
 * GET /api/dataset/datasets - 获取知识库列表
 */
export async function loader({ request }: LoaderFunctionArgs) {
    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        // 检查 JWT 是否存在
        if (!frontendJWT) {
            console.error('[API] Dataset List - JWT不存在');
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                {
                    status: 401,
                    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';

        console.log('[API] Dataset List - 获取知识库列表:', { page, limit });

        // 转发请求到 FastAPI
        const apiUrl = `${API_BASE_URL}/dify-dataset/datasets?page=${page}&limit=${limit}`;
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
        });

        const data = await response.json();

        console.log('[API] Dataset List - Success');
        return new Response(JSON.stringify(data), {
            status: response.status,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('[API] Dataset List - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to get datasets' }),
            {
                status: 500,
                headers: { 'Content-Type': 'application/json' },
            }
        );
    }
}
