import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { books } from '@/lib/db/schema';
import { eq, ilike, and, sql } from 'drizzle-orm';
import { BookSearchFilters, PaginatedResponse, Book } from '@/lib/types';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    
    // 分页参数
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '10');
    const offset = (page - 1) * pageSize;

    // 搜索参数
    const filters: BookSearchFilters = {
      title: searchParams.get('title') || undefined,
      author: searchParams.get('author') || undefined,
      isbn: searchParams.get('isbn') || undefined,
      classificationNo: searchParams.get('classificationNo') || undefined,
      status: (searchParams.get('status') as 'normal' | 'damaged' | 'removed') || undefined,
      available: searchParams.get('available') === 'true' ? true : undefined,
    };

    // 构建查询条件
    const conditions = [];
    
    if (filters.title) {
      conditions.push(ilike(books.title, `%${filters.title}%`));
    }
    
    if (filters.author) {
      conditions.push(sql`${books.authors} && ARRAY[${filters.author}]`);
    }
    
    if (filters.isbn) {
      conditions.push(eq(books.isbn, filters.isbn));
    }
    
    if (filters.classificationNo) {
      conditions.push(eq(books.classificationNo, filters.classificationNo));
    }
    
    if (filters.status) {
      conditions.push(eq(books.status, filters.status as 'normal' | 'damaged' | 'removed'));
    }
    
    if (filters.available) {
      conditions.push(sql`${books.availableCopies} > 0`);
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    // 获取总数
    const totalResult = await db
      .select({ count: sql<number>`count(*)` })
      .from(books)
      .where(whereClause);
    
    const total = totalResult[0].count;

    // 获取分页数据
    const booksData = await db
      .select()
      .from(books)
      .where(whereClause)
      .limit(pageSize)
      .offset(offset)
      .orderBy(books.createdAt);

    const response: PaginatedResponse<Book> = {
      data: booksData,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };

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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const newBook = await db
      .insert(books)
      .values({
        ...body,
        availableCopies: body.totalCopies || 1,
      })
      .returning();

    return NextResponse.json({ 
      success: true, 
      data: newBook[0],
      message: 'Book created successfully'
    });
  } catch (error) {
    console.error('Error creating book:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to create book' },
      { status: 500 }
    );
  }
}
