/**
 * 匹配配置API
 * 获取匹配类型和价格配置
 */

import { NextRequest, NextResponse } from 'next/server'
import { getConfig } from '@/lib/db'

// 默认匹配配置
const DEFAULT_MATCH_CONFIG = {
  matchTypes: [
    { id: 'partner', label: '创业合伙', matchLabel: '创业伙伴', icon: '⭐', matchFromDB: true, showJoinAfterMatch: false, price: 1, enabled: true },
    { id: 'investor', label: '资源对接', matchLabel: '资源对接', icon: '👥', matchFromDB: false, showJoinAfterMatch: true, price: 1, enabled: true },
    { id: 'mentor', label: '导师顾问', matchLabel: '商业顾问', icon: '❤️', matchFromDB: false, showJoinAfterMatch: true, price: 1, enabled: true },
    { id: 'team', label: '团队招募', matchLabel: '加入项目', icon: '🎮', matchFromDB: false, showJoinAfterMatch: true, price: 1, enabled: true }
  ],
  freeMatchLimit: 3,
  matchPrice: 1,
  settings: {
    enableFreeMatches: true,
    enablePaidMatches: true,
    maxMatchesPerDay: 10
  }
}

/**
 * GET - 获取匹配配置
 */
export async function GET(request: NextRequest) {
  try {
    // 优先从数据库读取
    let config = null
    try {
      config = await getConfig('match_config')
    } catch (e) {
      console.log('[MatchConfig] 数据库读取失败，使用默认配置')
    }
    
    // 合并默认配置
    const finalConfig = {
      ...DEFAULT_MATCH_CONFIG,
      ...(config || {})
    }
    
    // 只返回启用的匹配类型
    const enabledTypes = finalConfig.matchTypes.filter((t: any) => t.enabled !== false)
    
    return NextResponse.json({
      success: true,
      data: {
        matchTypes: enabledTypes,
        freeMatchLimit: finalConfig.freeMatchLimit,
        matchPrice: finalConfig.matchPrice,
        settings: finalConfig.settings
      },
      source: config ? 'database' : 'default'
    })
    
  } catch (error) {
    console.error('[MatchConfig] GET错误:', error)
    
    // 出错时返回默认配置
    return NextResponse.json({
      success: true,
      data: {
        matchTypes: DEFAULT_MATCH_CONFIG.matchTypes,
        freeMatchLimit: DEFAULT_MATCH_CONFIG.freeMatchLimit,
        matchPrice: DEFAULT_MATCH_CONFIG.matchPrice,
        settings: DEFAULT_MATCH_CONFIG.settings
      },
      source: 'fallback'
    })
  }
}
