import { json, type LoaderFunctionArgs } from '@remix-run/node';
import { difyClient } from '../services/dify-client.server';
import { getSessionInfo, commitSession } from '../utils/session.server';

export async function loader({ request }: LoaderFunctionArgs) {
    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);
        const { session } = await getSessionInfo(request);

        // 检查 JWT 是否存在
        if (!frontendJWT) {
            console.error('❌ [API] Conversations API - JWT不存在');
            return json(
                { data: [], error: 'JWT认证失败，请重新登录' },
                {
                    status: 401,
                    headers: {
                        'Set-Cookie': await commitSession(session),
                    },
                }
            );
        }

        console.log('💬 [API] Conversations API - 获取会话列表:', {
            hasJWT: !!frontendJWT
        });

        const data = await difyClient.getConversations(frontendJWT);

        console.log('✅ [API] Conversations API - Success');

        return json(data, {
            headers: {
                'Set-Cookie': await commitSession(session),
            },
        });
    } catch (error: any) {
        console.error('❌ [API] Conversations API - Error:', error);

        // 检查是否是JWT认证失败
        const status = error.message?.includes('JWT认证失败') ? 401 : 500;

        return json(
            {
                data: [],
                error: error.message || 'Failed to fetch conversations'
            },
            {
                status,
                headers: {
                    'Set-Cookie': await commitSession((await getSessionInfo(request)).session),
                },
            }
        );
    }
} 