import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { books, reviews } from '@/lib/db/schema';
import { eq, avg, count } from 'drizzle-orm';

export async function GET(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const bookId = parseInt(id);
    
    if (isNaN(bookId)) {
      return NextResponse.json(
        { success: false, error: 'Invalid book ID' },
        { status: 400 }
      );
    }

    // 获取图书基本信息
    const book = await db
      .select()
      .from(books)
      .where(eq(books.bookId, bookId))
      .limit(1);

    if (book.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Book not found' },
        { status: 404 }
      );
    }

    // 获取评价统计
    const reviewStats = await db
      .select({
        averageRating: avg(reviews.rating),
        reviewCount: count(reviews.reviewId),
      })
      .from(reviews)
      .where(eq(reviews.bookId, bookId));

    const bookWithDetails = {
      ...book[0],
      averageRating: reviewStats[0].averageRating || 0,
      reviewCount: reviewStats[0].reviewCount || 0,
    };

    return NextResponse.json({ 
      success: true, 
      data: bookWithDetails 
    });
  } catch (error) {
    console.error('Error fetching book:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch book' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const bookId = parseInt(id);
    const body = await request.json();
    
    if (isNaN(bookId)) {
      return NextResponse.json(
        { success: false, error: 'Invalid book ID' },
        { status: 400 }
      );
    }

    const updatedBook = await db
      .update(books)
      .set({
        ...body,
        updatedAt: new Date(),
      })
      .where(eq(books.bookId, bookId))
      .returning();

    if (updatedBook.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Book not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ 
      success: true, 
      data: updatedBook[0],
      message: 'Book updated successfully'
    });
  } catch (error) {
    console.error('Error updating book:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update book' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const bookId = parseInt(id);
    
    if (isNaN(bookId)) {
      return NextResponse.json(
        { success: false, error: 'Invalid book ID' },
        { status: 400 }
      );
    }

    // 软删除：更新状态为 removed
    const deletedBook = await db
      .update(books)
      .set({
        status: 'removed',
        availableCopies: 0,
        updatedAt: new Date(),
      })
      .where(eq(books.bookId, bookId))
      .returning();

    if (deletedBook.length === 0) {
      return NextResponse.json(
        { success: false, error: 'Book not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ 
      success: true, 
      message: 'Book removed successfully'
    });
  } catch (error) {
    console.error('Error deleting book:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete book' },
      { status: 500 }
    );
  }
}
