/**
 * 匹配用户API
 * 从数据库中查询用户进行匹配
 */

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

/**
 * POST - 获取匹配的用户
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, matchType } = body
    
    if (!userId) {
      return NextResponse.json({ success: false, message: '缺少用户ID' }, { status: 400 })
    }
    
    // 从数据库查询其他用户（排除自己）
    // 宽松条件：只要是注册用户就可以匹配
    const users = await query(`
      SELECT 
        id,
        nickname,
        avatar,
        wechat as wechatId,
        wechat_id,
        phone,
        introduction,
        created_at
      FROM users 
      WHERE id != ?
      ORDER BY created_at DESC
      LIMIT 20
    `, [userId]) as any[]
    
    if (!users || users.length === 0) {
      return NextResponse.json({
        success: false,
        message: '暂无匹配用户',
        data: null
      })
    }
    
    // 随机选择一个用户
    const randomUser = users[Math.floor(Math.random() * users.length)]
    
    // 构建匹配结果
    const wechat = randomUser.wechatId || randomUser.wechat_id || ''
    const matchResult = {
      id: randomUser.id,
      nickname: randomUser.nickname || '微信用户',
      avatar: randomUser.avatar || '',
      wechat: wechat,
      phone: randomUser.phone ? randomUser.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '',
      introduction: randomUser.introduction || '来自Soul创业派对的伙伴',
      tags: ['创业者', matchType === 'partner' ? '找伙伴' : 
             matchType === 'investor' ? '资源对接' :
             matchType === 'mentor' ? '导师顾问' : '团队招募'],
      matchScore: Math.floor(Math.random() * 20) + 80,
      commonInterests: [
        { icon: '📚', text: '都在读《创业派对》' },
        { icon: '💼', text: '对创业感兴趣' },
        { icon: '🎯', text: '相似的发展方向' }
      ]
    }
    
    return NextResponse.json({
      success: true,
      data: matchResult,
      totalUsers: users.length
    })
    
  } catch (error) {
    console.error('[Match Users] Error:', error)
    return NextResponse.json({
      success: false,
      message: '匹配失败',
      error: String(error)
    }, { status: 500 })
  }
}
