// app/api/book/chapter/[id]/route.ts
// 获取章节详情 - 从数据库读取，支持小程序和Web端
// 更新: 2026-01-25 改为从MySQL数据库读取章节内容

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

// 免费章节列表
const FREE_CHAPTERS = ['preface', 'epilogue', '1.1', 'appendix-1', 'appendix-2', 'appendix-3']

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: chapterId } = await params
    console.log('[Chapter API] 请求章节:', chapterId)
    
    // 从数据库查询章节
    const results = await query(
      `SELECT id, part_id, part_title, chapter_id, chapter_title, section_title, 
              content, word_count, is_free, price, sort_order, status, updated_at
       FROM chapters 
       WHERE id = ? AND status = 'published'`,
      [chapterId]
    ) as any[]
    
    if (!results || results.length === 0) {
      console.log('[Chapter API] 章节不存在:', chapterId)
      return NextResponse.json(
        { error: '章节不存在', success: false },
        { status: 404 }
      )
    }
    
    const chapter = results[0]
    const isFree = chapter.is_free || FREE_CHAPTERS.includes(chapterId)
    
    console.log('[Chapter API] 返回章节内容:', chapterId, '长度:', chapter.content?.length || 0)

    // 返回小程序兼容的格式
    return NextResponse.json({
      success: true,
      id: chapter.id,
      title: chapter.section_title,
      content: chapter.content,
      partTitle: chapter.part_title,
      chapterTitle: chapter.chapter_title,
      sectionTitle: chapter.section_title,
      words: chapter.word_count,
      updateTime: chapter.updated_at,
      isFree,
      price: chapter.price,
      needPurchase: !isFree
    })
  } catch (error) {
    console.error('[Chapter API] 获取章节失败:', error)
    return NextResponse.json(
      { error: '获取章节失败', success: false },
      { status: 500 }
    )
  }
}
