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

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

    if (!borrowId) {
      return NextResponse.json(
        { success: false, error: 'Borrow ID is required' },
        { status: 400 }
      );
    }

    // 开始事务
    const result = await db.transaction(async (tx) => {
      // 查找借阅记录
      const borrowRecord = await tx
        .select()
        .from(borrowRecords)
        .where(eq(borrowRecords.borrowId, borrowId))
        .limit(1);

      if (borrowRecord.length === 0) {
        throw new Error('Borrow record not found');
      }

      if (borrowRecord[0].status !== 'borrowed') {
        throw new Error('Book is not currently borrowed');
      }

      // 检查续借次数限制
      const maxRenewTimes = 2; // 最多续借2次，可以从系统设置中读取
      if (borrowRecord[0].renewTimes >= maxRenewTimes) {
        throw new Error(`Maximum renewal limit (${maxRenewTimes}) reached`);
      }

      // 检查是否有其他学生预约此书
      const hasReservation = await tx
        .select()
        .from(reservations)
        .where(
          and(
            eq(reservations.bookId, borrowRecord[0].bookId),
            eq(reservations.status, 'waiting')
          )
        )
        .limit(1);

      if (hasReservation.length > 0) {
        throw new Error('Cannot renew: book is reserved by another student');
      }

      // 计算新的到期日期（续借30天）
      const currentDueDate = new Date(borrowRecord[0].dueDate);
      const newDueDate = addDays(currentDueDate, 30);

      // 更新借阅记录
      const updatedBorrow = await tx
        .update(borrowRecords)
        .set({
          dueDate: newDueDate.toISOString().split('T')[0],
          renewTimes: sql`${borrowRecords.renewTimes} + 1`,
          updatedAt: new Date(),
        })
        .where(eq(borrowRecords.borrowId, borrowId))
        .returning();

      return updatedBorrow[0];
    });

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