/**
 * GET /api/v3/dify/area-datasets - 获取所有知识库绑定列表（管理员）
 * POST /api/v3/dify/area-datasets - 创建知识库绑定
 *
 * 权限说明：
 * GET: @require_permission_v2("dify:dataset:manage")
 * POST: @require_permission_v2("dify:dataset:manage")
 */

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

/**
 * GET - 获取所有知识库绑定列表
 */
export async function loader({ request }: LoaderFunctionArgs) {
    try {
        const { frontendJWT } = await getUserSession(request);

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

        // 获取查询参数
        const url = new URL(request.url);
        const area = url.searchParams.get('area');
        const only_enabled = url.searchParams.get('only_enabled');
        const page = url.searchParams.get('page') || '1';
        const page_size = url.searchParams.get('page_size') || '20';

        // 构建查询参数
        const params = new URLSearchParams();
        if (area) params.append('area', area);
        if (only_enabled !== null) params.append('only_enabled', only_enabled);
        params.append('page', page);
        params.append('page_size', page_size);

        console.log('[API V3] Get All Area Datasets', { area, only_enabled, page, page_size });

        // 转发请求到后端
        const apiUrl = `${API_BASE_URL}/v3/dify/area-datasets?${params}`;
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
        });

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

    } catch (error: any) {
        console.error('[API V3] Get All Area Datasets - Error:', error.message);
        return json(
            { error: error.message || 'Failed to get all area datasets' },
            { status: 500 }
        );
    }
}

/**
 * POST - 创建知识库绑定
 */
export async function action({ request }: LoaderFunctionArgs) {
    try {
        const { frontendJWT } = await getUserSession(request);

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

        const body = await request.json();
        console.log('[API V3] Create Area Dataset', body);

        // 转发创建请求到后端
        const apiUrl = `${API_BASE_URL}/v3/dify/area-datasets`;
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${frontendJWT}`,
            },
            body: JSON.stringify(body),
        });

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

    } catch (error: any) {
        console.error('[API V3] Create Area Dataset - Error:', error.message);
        return json(
            { error: error.message || 'Failed to create area dataset' },
            { status: 500 }
        );
    }
}
