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 {
        const { user, session } = await getSessionInfo(request);

        // ('💬 Conversations API - User:', user);

        const data = await difyClient.getConversations(user);

        // ('✅ Conversations API - Success:', data);

        return json(data, {
            headers: {
                'Set-Cookie': await commitSession(session),
            },
        });
    } catch (error: any) {
        console.error('❌ Conversations API - Error:', error);
        return json(
            {
                data: [],
                error: error.message || 'Failed to fetch conversations'
            },
            {
                status: 500,
                headers: {
                    'Set-Cookie': await commitSession((await getSessionInfo(request)).session),
                },
            }
        );
    }
} 