import { type ActionFunctionArgs } from '@remix-run/node';
import { difyClient } from '~/api/dify-chat/client.server';

/**
 * POST /api/messages/:messageId/feedbacks - 提交消息反馈
 */
export async function action({ request, params }: ActionFunctionArgs) {
    if (request.method !== 'POST') {
        return new Response('Method not allowed', { status: 405 });
    }

    try {
        // 获取用户会话信息和 JWT
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        // 检查 JWT 是否存在
        if (!frontendJWT) {
            console.error('[API] Message Feedback - JWT不存在');
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                {
                    status: 401,
                    headers: { 'Content-Type': 'application/json' },
                }
            );
        }

        const { messageId } = params;
        if (!messageId) {
            return new Response(
                JSON.stringify({ error: '缺少 messageId 参数' }),
                {
                    status: 400,
                    headers: { 'Content-Type': 'application/json' },
                }
            );
        }

        const body = await request.json();
        const { rating } = body;

        console.log('[API] Message Feedback - 提交反馈:', {
            messageId,
            rating,
        });

        const result = await difyClient.updateMessageFeedback(messageId, rating, frontendJWT);

        console.log('[API] Message Feedback - Success');
        return new Response(JSON.stringify(result), {
            status: 200,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('[API] Message Feedback - Error:', error.message);
        const sm = error.message?.match(/(\d{3})/); const os = sm ? parseInt(sm[1]) : 0;
        const status = error.message?.includes('JWT认证失败') ? 401 : os >= 400 && os < 500 ? os : 500;
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to submit feedback' }),
            {
                status,
                headers: { 'Content-Type': 'application/json' },
            }
        );
    }
}
