/**
 * Server Setting API路由
 * 根据code获取服务端配置
 */

import { NextRequest, NextResponse } from 'next/server';

/**
 * 根据code获取服务端配置
 * POST /api/server-setting/find_by_code
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { code } = body;

    console.log('📋 获取服务端配置请求:', { code });

    if (!code) {
      return NextResponse.json({
        code: 400,
        successful: false,
        message: 'code parameter is required',
        data: null
      }, { status: 400 });
    }

    // 根据code返回不同的配置，匹配实际API格式
    let responseData = null;
    
    switch (code) {
      case 'sso_config':
        // SSO配置 - 控制Google登录按钮显示
        responseData = {
          id: 8,
          code: 'sso_config',
          value: '{\n  "show": true\n}',
          note: 'sso 入口',
          updated_at: new Date().toISOString().slice(0, 19)
        };
        break;
      
      case 'home_tabs':
        // 首页标签配置示例
        responseData = {
          id: 1,
          code: 'home_tabs',
          value: JSON.stringify([
            {
              id: '1',
              title: '推荐',
              subtitle: '为您推荐',
              status: 1,
              sortOrder: 1,
              videos: []
            }
          ], null, 2),
          note: '首页标签配置',
          updated_at: new Date().toISOString().slice(0, 19)
        };
        break;

      case 'video_modification':
        // 视频修改功能配置 - 控制视频编辑笔图标显示
        // 可以通过查询参数 ?show=false 来测试隐藏功能
        const url = new URL(request.url);
        const showParam = url.searchParams.get('show');
        const showValue = showParam !== null ? showParam === 'true' : true; // 默认显示

        responseData = {
          id: 9,
          code: 'video_modification',
          value: `{\n  "show": ${showValue}\n}`,
          note: '视频修改功能开关',
          updated_at: new Date().toISOString().slice(0, 19)
        };
        console.log('📋 video_modification配置:', { showParam, showValue, value: responseData.value });
        break;
        
      default:
        // 默认返回空配置
        responseData = {
          id: 0,
          code: code,
          value: '{}',
          note: '默认配置',
          updated_at: new Date().toISOString().slice(0, 19)
        };
        break;
    }

    const response = {
      code: 0,
      successful: true,
      message: 'Success',
      data: responseData
    };

    console.log('✅ 服务端配置获取成功:', { code, hasData: !!responseData });
    return NextResponse.json(response);

  } catch (error) {
    console.error('❌ 获取服务端配置失败:', error);
    return NextResponse.json({
      code: 500,
      successful: false,
      message: 'Internal server error',
      data: null
    }, { status: 500 });
  }
}
