<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Route;
use Kylin\Library\Models\Book;
use Kylin\Library\Models\BorrowRecord;
use Kylin\Library\Models\Reader;
use Kylin\Library\Models\Seat;
use Kylin\Library\Models\SeatReservation;

/*
|--------------------------------------------------------------------------
| 图书馆 API 路由
|--------------------------------------------------------------------------
|
| 依据《公共图书馆法》第三十三条、第四十三条：
| 保护读者信息，图书借阅归还管理。
| 依据《个人信息保护法》第六条：最小必要原则。
|
*/

// 图书管理
Route::prefix('books')->group(function () {
    Route::get('/', function () {
        return Book::query()->paginate(20);
    });
    Route::get('/{id}', function ($id) {
        return Book::findOrFail($id);
    });
    Route::get('/search', function () {
        $keyword = request('keyword');
        return Book::where('title', 'like', "%{$keyword}%")
            ->orWhere('author', 'like', "%{$keyword}%")
            ->orWhere('isbn', $keyword)
            ->paginate(20);
    });
});

// 读者管理
Route::prefix('readers')->group(function () {
    Route::get('/', function () {
        return Reader::query()->paginate(20);
    });
    Route::get('/{id}', function ($id) {
        return Reader::with('borrowRecords')->findOrFail($id);
    });
});

// 借阅管理
Route::prefix('borrows')->group(function () {
    Route::get('/', function () {
        return BorrowRecord::with(['reader', 'book'])
            ->orderByDesc('id')
            ->paginate(20);
    });
    Route::get('/overdue', function () {
        return BorrowRecord::with(['reader', 'book'])
            ->where('status', 'borrowed')
            ->where('due_at', '<', now())
            ->paginate(20);
    });
});

// 座位管理
Route::prefix('seats')->group(function () {
    Route::get('/', function () {
        return Seat::query()->paginate(50);
    });
    Route::get('/available', function () {
        return Seat::where('status', 'available')->paginate(50);
    });
});

// 座位预约
Route::prefix('reservations')->group(function () {
    Route::get('/', function () {
        return SeatReservation::with(['reader', 'seat'])
            ->orderByDesc('reserved_date')
            ->paginate(20);
    });
    Route::get('/today', function () {
        return SeatReservation::with(['reader', 'seat'])
            ->where('reserved_date', today())
            ->paginate(50);
    });
});