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

function normalizeApp(payload: any) {
    const app = payload?.data?.data || payload?.data || null;
    if (!app) return null;
    return {
        app_id: String(app.appId),
        app_name: app.appName,
        description: app.description || '',
        is_default: Boolean(app.isDefault),
        type: 'rag',
        created_at: '',
        updated_at: '',
    };
}

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

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

        const response = await fetch(`${API_BASE_URL}/v3/rag/apps/default`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${frontendJWT}`,
            },
        });

        const data = await response.json();
        return json({ data: normalizeApp(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 }
        );
    }
}
