/**
 * 数据库初始化API
 * 创建数据库表结构和默认配置
 */

import { NextResponse } from 'next/server'
import { initDatabase } from '@/lib/db'

/**
 * POST - 初始化数据库
 */
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { adminToken } = body

    // 简单的管理员验证
    if (adminToken !== 'init_db_2025') {
      return NextResponse.json({
        success: false,
        error: '无权限执行此操作'
      }, { status: 403 })
    }

    console.log('[DB Init] 开始初始化数据库...')

    await initDatabase()

    console.log('[DB Init] 数据库初始化完成')

    return NextResponse.json({
      success: true,
      data: {
        message: '数据库初始化成功',
        timestamp: new Date().toISOString()
      }
    })

  } catch (error) {
    console.error('[DB Init] 数据库初始化失败:', error)
    return NextResponse.json({
      success: false,
      error: '数据库初始化失败: ' + (error as Error).message
    }, { status: 500 })
  }
}

/**
 * GET - 检查数据库状态
 */
export async function GET() {
  try {
    const { query } = await import('@/lib/db')
    
    // 检查数据库连接
    await query('SELECT 1')
    
    // 检查表是否存在
    const tables = await query(`
      SELECT TABLE_NAME 
      FROM INFORMATION_SCHEMA.TABLES 
      WHERE TABLE_SCHEMA = DATABASE()
    `) as any[]
    
    const tableNames = tables.map(t => t.TABLE_NAME)
    
    return NextResponse.json({
      success: true,
      data: {
        connected: true,
        tables: tableNames,
        tablesCount: tableNames.length
      }
    })

  } catch (error) {
    console.error('[DB Status] 检查数据库状态失败:', error)
    return NextResponse.json({
      success: false,
      error: '数据库连接失败: ' + (error as Error).message
    }, { status: 500 })
  }
}