import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { borrowRecords, books, students, fines } from '@/lib/db/schema';
import { eq, sql } from 'drizzle-orm';
import { differenceInDays } 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 returnDate = new Date();
      const dueDate = new Date(borrowRecord[0].dueDate);
      const overdueDays = differenceInDays(returnDate, dueDate);

      // 计算罚款
      let fineAmount = 0;
      if (overdueDays > 0) {
        const finePerDay = 1.0; // 每天1元罚款，可以从系统设置中读取
        fineAmount = overdueDays * finePerDay;
      }

      // 更新借阅记录
      const updatedBorrow = await tx
        .update(borrowRecords)
        .set({
          returnDate: returnDate.toISOString().split('T')[0],
          status: overdueDays > 0 ? 'overdue' : 'returned',
          fineAmount: fineAmount.toString(),
          updatedAt: new Date(),
        })
        .where(eq(borrowRecords.borrowId, borrowId))
        .returning();

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

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

      // 如果有罚款，创建罚款记录
      if (fineAmount > 0) {
        await tx
          .insert(fines)
          .values({
            studentId: borrowRecord[0].studentId,
            borrowId: borrowId,
            fineType: 'overdue',
            amount: fineAmount.toString(),
            reason: `Overdue return: ${overdueDays} days late`,
            status: 'unpaid',
          });
      }

      return {
        ...updatedBorrow[0],
        overdueDays,
        fineAmount,
      };
    });

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