import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { borrowRecords, books, students } from '@/lib/db/schema';
import { eq, and, sql } from 'drizzle-orm';
import { addDays } from 'date-fns';

export async function POST(request: NextRequest) {
  try {
    const { bookId, studentId } = await request.json();

    if (!bookId || !studentId) {
      return NextResponse.json(
        { success: false, error: 'Book ID and Student ID are required' },
        { status: 400 }
      );
    }

    // 开始事务
    const result = await db.transaction(async (tx) => {
      // 检查图书是否可借
      const book = await tx
        .select()
        .from(books)
        .where(eq(books.bookId, bookId))
        .limit(1);

      if (book.length === 0) {
        throw new Error('Book not found');
      }

      if (book[0].availableCopies <= 0) {
        throw new Error('Book is not available for borrowing');
      }

      if (book[0].status !== 'normal') {
        throw new Error('Book is not in normal status');
      }

      // 检查学生状态
      const student = await tx
        .select()
        .from(students)
        .where(eq(students.studentId, studentId))
        .limit(1);

      if (student.length === 0) {
        throw new Error('Student not found');
      }

      if (student[0].accountStatus !== 'active') {
        throw new Error('Student account is not active');
      }

      if (student[0].currentBorrow >= student[0].maxBorrow) {
        throw new Error('Student has reached maximum borrow limit');
      }

      // 检查是否已借阅此书
      const existingBorrow = await tx
        .select()
        .from(borrowRecords)
        .where(
          and(
            eq(borrowRecords.bookId, bookId),
            eq(borrowRecords.studentId, studentId),
            eq(borrowRecords.status, 'borrowed')
          )
        )
        .limit(1);

      if (existingBorrow.length > 0) {
        throw new Error('Student has already borrowed this book');
      }

      // 计算到期日期（默认30天）
      const borrowDate = new Date();
      const dueDate = addDays(borrowDate, 30);

      // 创建借阅记录
      const newBorrow = await tx
        .insert(borrowRecords)
        .values({
          bookId,
          studentId,
          borrowDate: borrowDate.toISOString().split('T')[0],
          dueDate: dueDate.toISOString().split('T')[0],
          status: 'borrowed',
        })
        .returning();

      // 更新图书可借数量
      await tx
        .update(books)
        .set({
          availableCopies: sql`${books.availableCopies} - 1`,
          updatedAt: new Date(),
        })
        .where(eq(books.bookId, bookId));

      // 更新学生当前借阅数量
      await tx
        .update(students)
        .set({
          currentBorrow: sql`${students.currentBorrow} + 1`,
          updatedAt: new Date(),
        })
        .where(eq(students.studentId, studentId));

      return newBorrow[0];
    });

    return NextResponse.json({
      success: true,
      data: result,
      message: 'Book borrowed successfully',
    });
  } catch (error) {
    console.error('Error borrowing book:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to borrow book' 
      },
      { status: 500 }
    );
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const studentId = searchParams.get('studentId');
    const status = searchParams.get('status');
    
    // 构建查询条件
    const conditions = [];
    
    if (studentId) {
      conditions.push(eq(borrowRecords.studentId, parseInt(studentId)));
    }
    
    if (status) {
      conditions.push(eq(borrowRecords.status, status as 'borrowed' | 'returned' | 'overdue'));
    }

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

    // 获取借阅记录，包含图书和学生信息
    const borrows = await db
      .select({
        borrowId: borrowRecords.borrowId,
        borrowDate: borrowRecords.borrowDate,
        dueDate: borrowRecords.dueDate,
        returnDate: borrowRecords.returnDate,
        renewTimes: borrowRecords.renewTimes,
        status: borrowRecords.status,
        fineAmount: borrowRecords.fineAmount,
        notes: borrowRecords.notes,
        book: {
          bookId: books.bookId,
          isbn: books.isbn,
          title: books.title,
          authors: books.authors,
          publisher: books.publisher,
        },
        student: {
          studentId: students.studentId,
          stuNo: students.stuNo,
          name: students.name,
          department: students.department,
        },
      })
      .from(borrowRecords)
      .leftJoin(books, eq(borrowRecords.bookId, books.bookId))
      .leftJoin(students, eq(borrowRecords.studentId, students.studentId))
      .where(whereClause)
      .orderBy(borrowRecords.createdAt);

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