<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Book;
use App\Models\BookIssue;
use Illuminate\Http\Request;

// F1 — Library circulation: issue / return / fines. Book CRUD lives in the
// generic controller; this handles the lending workflow.
class LibraryController extends Controller
{
    private const FINE_PER_DAY = 10;

    public function issues(Request $request)
    {
        $rows = BookIssue::with('book:id,title,author')
            ->when($request->query('status'), fn ($q, $s) => $q->where('status', $s))
            ->orderByDesc('created_at')->limit(1000)->get();

        return response()->json(['data' => $rows]);
    }

    public function issue(Request $request)
    {
        $data = $request->validate([
            'book_id' => ['required', 'exists:books,id'],
            'person_name' => ['required', 'string'],
            'person_type' => ['nullable', 'in:student,staff'],
            'due_date' => ['required', 'string'],
        ]);
        $book = Book::findOrFail($data['book_id']);
        if ($book->available < 1) {
            return response()->json(['message' => 'No copies available.'], 422);
        }

        $issue = BookIssue::create([
            'book_id' => $book->id,
            'person_name' => $data['person_name'],
            'person_type' => $data['person_type'] ?? 'student',
            'issue_date' => now()->toDateString(),
            'due_date' => $data['due_date'],
        ]);
        $book->decrement('available');
        ActivityLog::record('create', 'library', "Issued '{$book->title}' to {$data['person_name']}", $issue);

        return response()->json(['data' => $issue->load('book:id,title,author')], 201);
    }

    public function returnBook(BookIssue $issue)
    {
        if ($issue->status === 'returned') {
            return response()->json(['message' => 'Already returned.'], 422);
        }
        $today = now()->toDateString();
        $daysLate = max(0, (int) floor((strtotime($today) - strtotime($issue->due_date)) / 86400));
        $issue->update(['return_date' => $today, 'fine' => $daysLate * self::FINE_PER_DAY, 'status' => 'returned']);
        $issue->book?->increment('available');
        ActivityLog::record('update', 'library', "Returned '{$issue->book?->title}' (fine {$issue->fine})", $issue);

        return response()->json(['data' => $issue->fresh()->load('book:id,title,author')]);
    }
}
