import { type ActionFunctionArgs } from '@remix-run/node';
import { API_BASE_URL } from '~/config/api-config';

/**
 * PATCH /api/dataset/datasets/:datasetId/documents/status/:action - 批量更新文档状态
 * Dify API: PATCH /datasets/{dataset_id}/documents/status/{action}
 * action: enable / disable / archive / un_archive
 */
export async function action({ request, params }: ActionFunctionArgs) {
    try {
        const { getUserSession } = await import("~/api/login/auth.server");
        const { frontendJWT } = await getUserSession(request);

        if (!frontendJWT) {
            return new Response(
                JSON.stringify({ error: 'JWT认证失败，请重新登录' }),
                { status: 401, headers: { 'Content-Type': 'application/json' } }
            );
        }

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

        // 验证action参数
        const validActions = ['enable', 'disable', 'archive', 'un_archive'];
        if (!validActions.includes(statusAction)) {
            return new Response(
                JSON.stringify({ error: `无效的action参数，有效值: ${validActions.join(', ')}` }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

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

        if (!document_ids || !Array.isArray(document_ids) || document_ids.length === 0) {
            return new Response(
                JSON.stringify({ error: '缺少 document_ids 参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        console.log('[API] Update Documents Status:', { datasetId, action: statusAction, document_ids });

        // 转发请求到 FastAPI -> Dify API
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/status/${statusAction}`;
        const response = await fetch(apiUrl, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
            body: JSON.stringify({ document_ids }),
        });

        const data = await response.json();

        return new Response(JSON.stringify(data), {
            status: response.status,
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error: any) {
        console.error('[API] Update Documents Status - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to update documents status' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
