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

/**
 * PATCH /api/dataset/datasets/:datasetId/documents/:documentId/segments/:segmentId/child_chunks/:childChunkId - 更新子分段
 * DELETE /api/dataset/datasets/:datasetId/documents/:documentId/segments/:segmentId/child_chunks/:childChunkId - 删除子分段
 *
 * Dify API:
 * - PATCH /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}/child_chunks/{child_chunk_id}
 * - DELETE /datasets/{dataset_id}/documents/{document_id}/segments/{segment_id}/child_chunks/{child_chunk_id}
 */
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, documentId, segmentId, childChunkId } = params;
        if (!datasetId || !documentId || !segmentId || !childChunkId) {
            return new Response(
                JSON.stringify({ error: '缺少必要参数' }),
                { status: 400, headers: { 'Content-Type': 'application/json' } }
            );
        }

        const method = request.method;
        const apiUrl = `${API_BASE_URL}/dify_dataset/datasets/${datasetId}/documents/${documentId}/segments/${segmentId}/child_chunks/${childChunkId}`;

        if (method === 'DELETE') {
            console.log('[API] Delete Child Chunk:', { datasetId, documentId, segmentId, childChunkId });

            const response = await fetch(apiUrl, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${frontendJWT}`,
                },
            });

            // Dify 删除子分段返回 204 No Content
            if (response.status === 204) {
                return new Response(
                    JSON.stringify({ result: 'success' }),
                    { status: 200, headers: { 'Content-Type': 'application/json' } }
                );
            }

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

        if (method === 'PATCH') {
            const body = await request.json();
            console.log('[API] Update Child Chunk:', { datasetId, documentId, segmentId, childChunkId, body });

            const response = await fetch(apiUrl, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${frontendJWT}`,
                },
                body: JSON.stringify(body),
            });

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

        return new Response(
            JSON.stringify({ error: 'Method not allowed' }),
            { status: 405, headers: { 'Content-Type': 'application/json' } }
        );

    } catch (error: any) {
        console.error('[API] Child Chunk Action - Error:', error.message);
        return new Response(
            JSON.stringify({ error: error.message || 'Failed to process child chunk request' }),
            { status: 500, headers: { 'Content-Type': 'application/json' } }
        );
    }
}
