package library.routes;

import static library.routes.Params.pathId;

import io.javalin.config.JavalinConfig;
import io.javalin.http.Context;
import library.domain.Loan;
import library.dto.NewLoan;
import library.errors.ValidationException;
import library.service.LoanService;

/**
 * HTTP in, HTTP out for checking out and returning books.
 *
 * Each handler describes the success path; failures are exceptions that
 * ErrorHandler turns into responses.
 */
public class LoanRoutes {

	private final LoanService service;

	public LoanRoutes(LoanService service) {
		this.service = service;
	}

	// Javalin 7: called from inside Javalin.create(config -> { ... })
	public void register(JavalinConfig config) {
		config.routes.post("/loans", ctx -> checkOut(ctx));
		config.routes.put("/loans/{id}/return", ctx -> returnBook(ctx));
	}

	// POST /loans { "bookId": 3, "memberId": 1 } → 201 with Location
	private void checkOut(Context ctx) {
		NewLoan body = ctx.bodyAsClass(NewLoan.class);
		if (body == null || body.bookId() == null || body.memberId() == null) {
			throw new ValidationException("bookId and memberId are required");
		}
		Loan created = service.checkOut(body.memberId(), body.bookId());
		ctx.status(201).header("Location", "/loans/" + created.loanId()).json(created);
	}

	// PUT /loans/{id}/return → 200 with the loan, no body needed. Idempotent.
	private void returnBook(Context ctx) {
		ctx.json(service.returnBook(pathId(ctx)));
	}
}
