/**
 * 推荐访问记录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 { referralCode, visitorOpenId, visitorId, source, page } = body
    
    if (!referralCode) {
      return NextResponse.json({
        success: false,
        error: '推荐码不能为空'
      }, { status: 400 })
    }
    
    // 查找推荐人
    const referrers = await query(
      'SELECT id FROM users WHERE referral_code = ?',
      [referralCode]
    ) as any[]
    
    if (referrers.length === 0) {
      return NextResponse.json({
        success: false,
        error: '推荐码无效'
      }, { status: 400 })
    }
    
    const referrerId = referrers[0].id
    
    // 记录访问（允许重复访问记录，用于统计总访问次数）
    try {
      await query(`
        INSERT INTO referral_visits (
          referrer_id, visitor_id, visitor_openid, source, page, created_at
        ) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
      `, [
        referrerId,
        visitorId || null,
        visitorOpenId || null,
        source || 'miniprogram',
        page || ''
      ])
      
      console.log(`[Referral Visit] 记录访问: 推荐人=${referrerId}, 访客openId=${visitorOpenId?.slice(0,10) || 'unknown'}`)
    } catch (insertError) {
      // 表可能不存在，尝试创建
      console.log('[Referral Visit] 插入失败，尝试创建表...')
      await query(`
        CREATE TABLE IF NOT EXISTS referral_visits (
          id INT AUTO_INCREMENT PRIMARY KEY,
          referrer_id VARCHAR(50) NOT NULL COMMENT '推广者ID',
          visitor_id VARCHAR(50) COMMENT '访客ID（可能为空）',
          visitor_openid VARCHAR(100) COMMENT '访客openId',
          source VARCHAR(50) DEFAULT 'miniprogram' COMMENT '来源：miniprogram/web/share',
          page VARCHAR(200) COMMENT '落地页路径',
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          INDEX idx_referrer_id (referrer_id),
          INDEX idx_visitor_id (visitor_id),
          INDEX idx_created_at (created_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
      `)
      
      // 重试插入
      await query(`
        INSERT INTO referral_visits (
          referrer_id, visitor_id, visitor_openid, source, page, created_at
        ) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
      `, [
        referrerId,
        visitorId || null,
        visitorOpenId || null,
        source || 'miniprogram',
        page || ''
      ])
    }
    
    return NextResponse.json({
      success: true,
      message: '访问已记录'
    })
    
  } catch (error) {
    console.error('[Referral Visit] 错误:', error)
    // 即使出错也返回成功，不影响用户体验
    return NextResponse.json({
      success: true,
      message: '已处理'
    })
  }
}
