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);
        const url = new URL(request.url);
        const conversationId = url.searchParams.get('conversation_id');

        if (!conversationId) {
            return json(
                { error: 'conversation_id is required' },
                { status: 400 }
            );
        }

        // ('📨 Messages API - User:', user, 'ConversationId:', conversationId);

        const data = await difyClient.getConversationMessages(user, conversationId);

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

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