/**
 * GET /api/v3/dify/area-datasets/areas - 获取可用地区列表（管理员）
 */

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 }: LoaderFunctionArgs) {
    try {
        const { frontendJWT } = await getUserSession(request);

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

        console.log('[API V3] Get Available Areas');

        // 转发请求到后端
        const apiUrl = `${API_BASE_URL}/v3/dify/area-datasets/areas`;
        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 Available Areas - Error:', error.message);
        return json(
            { error: error.message || 'Failed to get available areas' },
            { status: 500 }
        );
    }
}
