package library.service;

import java.time.LocalDate;
import java.util.Optional;

import library.dao.BookDao;
import library.dao.LoanDao;
import library.dao.Transactions;
import library.domain.Book;
import library.domain.Loan;
import library.errors.ConflictException;
import library.errors.NotFoundException;

/**
 * Checking out and returning books.
 *
 * Each changes two tables (LOANS and BOOKS), so each runs as one transaction:
 * both changes happen, or neither does.
 */
public class LoanService {

	private static final int LOAN_DAYS = 14;

	private final LoanDao loanDao;
	private final BookDao bookDao;

	public LoanService(LoanDao loanDao, BookDao bookDao) {
		this.loanDao = loanDao;
		this.bookDao = bookDao;
	}

	// POST /loans: check out a book.
	//
	// One transaction: read and lock the book, insert the loan, mark the book
	// unavailable. If anything fails, all of it is rolled back, so there's never
	// a loan for a book still marked available, or the reverse.
	//
	// The book is read FOR UPDATE, which locks its row until the transaction
	// ends. If two members check out the same book at once, the second waits at
	// that read until the first commits, then sees available = FALSE and gets a
	// 409. Without the lock, both could read TRUE and both get the book.
	public Loan checkOut(int memberId, int bookId) {
		return Transactions.run(conn -> {
			Optional<Book> book = bookDao.findByIdForUpdate(conn, bookId);
			if (book.isEmpty()) {
				throw new NotFoundException("No book with id " + bookId);
			}
			if (!book.get().available()) {
				throw new ConflictException("Book " + bookId + " is already checked out");
			}
			LocalDate today = LocalDate.now();
			int loanId = loanDao.insert(conn, new Loan(null, bookId, memberId, today, today.plusDays(LOAN_DAYS), null));
			bookDao.setAvailable(conn, bookId, false);
			Optional<Loan> created = loanDao.findById(conn, loanId);
			if (created.isEmpty()) {
				throw new IllegalStateException("Loan " + loanId + " was inserted but can't be found");
			}
			return created.get();
		});
	}

	// PUT /loans/{id}/return → the returned loan. Idempotent: returning an
	// already-returned loan changes nothing and still succeeds.
	//
	// One transaction marks the loan returned and the book available.
	// markReturned only changes a loan that is still out, so if two returns of
	// the same loan arrive at once, only one of them makes the book available.
	public Loan returnBook(int loanId) {
		Optional<Loan> loan = loanDao.findById(loanId);
		if (loan.isEmpty()) {
			throw new NotFoundException("No loan with id " + loanId);
		}
		if (loan.get().returnedOn() != null) {
			return loan.get(); // already returned
		}
		int bookId = loan.get().bookId();
		return Transactions.run(conn -> {
			if (loanDao.markReturned(conn, loanId, LocalDate.now())) {
				bookDao.setAvailable(conn, bookId, true);
			}
			Optional<Loan> returned = loanDao.findById(conn, loanId);
			if (returned.isEmpty()) {
				throw new IllegalStateException("Loan " + loanId + " can't be found");
			}
			return returned.get();
		});
	}
}
