/**
 * PUT /api/v3/dify/area-datasets/{id} - 更新知识库绑定
 * DELETE /api/v3/dify/area-datasets/{id} - 删除知识库绑定
 */

import { type LoaderFunctionArgs, json } from '@remix-run/node';
import { API_BASE_URL } from '~/config/api-config';
import { getUserSession } from '~/api/login/auth.server';

export async function loader({ request, params }: LoaderFunctionArgs) {
    return json({ error: 'Method not allowed' }, { status: 405 });
}

/**
 * 更新知识库绑定
 */
export async function action({ request, params }: LoaderFunctionArgs) {
    try {
        const { frontendJWT } = await getUserSession(request);

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

        const { id } = params;
        const method = request.method;

        if (method === 'PUT') {
            // 更新知识库绑定
            const body = await request.json();
            console.log(`[API V3] Update Area Dataset: ${id}`, body);

            const apiUrl = `${API_BASE_URL}/v3/dify/area-datasets/${id}`;
            const response = await fetch(apiUrl, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${frontendJWT}`,
                },
                body: JSON.stringify(body),
            });

            const data = await response.json();
            return json(data, { status: response.status });

        } else if (method === 'DELETE') {
            // 删除知识库绑定
            console.log(`[API V3] Delete Area Dataset: ${id}`);

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

            const data = await response.json();
            return json(data, { status: response.status });

        } else {
            return json({ error: 'Method not allowed' }, { status: 405 });
        }

    } catch (error: any) {
        console.error('[API V3] Area Dataset Action - Error:', error.message);
        return json(
            { error: error.message || 'Operation failed' },
            { status: 500 }
        );
    }
}
