import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';

// GET: 获取多语言内容
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const group = searchParams.get('group'); // 获取指定分组
    const keys = searchParams.get('keys'); // 获取指定键名列表（逗号分隔）

    const client = getSupabaseClient();
    let query = client
      .from('i18n_content')
      .select('id, group_name, key_name, content_zh, content_ru, description, sort_order');

    if (group) {
      query = query.eq('group_name', group);
    } else if (keys) {
      const keyList = keys.split(',').map(k => k.trim());
      query = query.in('id', keyList);
    }

    const { data: content, error } = await query.order('sort_order', { ascending: true });

    if (error) {
      console.error('Error fetching i18n content:', error);
      return NextResponse.json(
        { success: false, error: '获取内容失败' },
        { status: 500 }
      );
    }

    // 转换为键值对格式
    const result: Record<string, { zh: string; ru: string }> = {};
    (content || []).forEach(item => {
      result[item.id] = {
        zh: item.content_zh || '',
        ru: item.content_ru || '',
      };
    });

    return NextResponse.json({ 
      success: true, 
      content: result,
      raw: content 
    });
  } catch (error) {
    console.error('Error fetching i18n content:', error);
    return NextResponse.json(
      { success: false, error: '获取内容失败' },
      { status: 500 }
    );
  }
}
