/**
 * GET /api/v3/dify/chat-apps/default - 获取默认对话应用
 *
 * 转发请求到后端 API，后端从配置文件读取默认对话应用
 * 参考文档：docs/new-dify/dify_api_doc.md - 对话应用多实例支持
 */

import { LoaderFunctionArgs, json } from '@remix-run/node';
import { API_BASE_URL } from '~/config/api-config';
import { getUserSession } from '~/api/login/auth.server';

export async function loader({ request }: LoaderFunctionArgs) {
    try {
        const { frontendJWT } = await getUserSession(request);

        if (!frontendJWT) {
            return json(
                { code: 401, message: 'JWT认证失败，请重新登录', data: null },
                { status: 401 }
            );
        }

        console.log('[API] Get Default Chat App - Forwarding to backend');

        // 转发请求到后端
        const apiUrl = `${API_BASE_URL}/v3/dify/chat-apps/default`;
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
        });

        const data = await response.json();
        console.log('[API] Get Default Chat App - Backend response:', data);

        return json(data, { status: response.status });

    } catch (error: any) {
        console.error('[API] Get Default Chat App - Error:', error.message);
        return json(
            { code: 500, message: error.message || 'Failed to get default chat app', data: null },
            { status: 500 }
        );
    }
}
