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

function normalizeApps(payload: any) {
    const apps = payload?.data?.data || payload?.data || [];
    return {
        data: Array.isArray(apps)
            ? apps.map((app: any) => ({
                app_id: String(app.appId),
                app_name: app.appName,
                description: app.description || '',
                is_default: Boolean(app.isDefault),
                type: 'rag',
                created_at: '',
                updated_at: '',
            }))
            : [],
        total: Array.isArray(apps) ? apps.length : 0,
        page: 1,
        page_size: Array.isArray(apps) ? apps.length : 0,
    };
}

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

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

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

        const data = await response.json();
        const normalized = normalizeApps(data);
        return json(normalized, { status: response.status });
    } catch (error: any) {
        console.error('[API] Get My Chat Apps - Error:', error.message);
        return json(
            { code: 500, message: error.message || 'Failed to get chat apps', data: { data: [], total: 0 } },
            { status: 500 }
        );
    }
}
