package library.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Optional;

import library.domain.Book;

/**
 * The SQL for BOOKS that checkout and return need.
 *
 * Both methods run inside a transaction (Transactions.run): they take the
 * transaction's Connection instead of opening their own, and leave SQLException
 * to the transaction to handle.
 */
public class BookDao {

	private static final String COLUMNS = "book_id, isbn, title, author, published_on, replacement_cost, available";

	// Checkout: the book, locked until the transaction ends.
	// FOR UPDATE makes a second checkout of the same book wait here until the
	// first one commits, and then it sees available = FALSE.
	public Optional<Book> findByIdForUpdate(Connection conn, int bookId) throws SQLException {
		String sql = "SELECT " + COLUMNS + " FROM BOOKS WHERE book_id = ? FOR UPDATE";
		try (PreparedStatement ps = conn.prepareStatement(sql)) {
			ps.setInt(1, bookId);
			try (ResultSet rs = ps.executeQuery()) {
				if (rs.next()) {
					return Optional.of(map(rs));
				}
				return Optional.empty();
			}
		}
	}

	// Checkout and return → false if no such book
	public boolean setAvailable(Connection conn, int bookId, boolean available) throws SQLException {
		String sql = "UPDATE BOOKS SET available = ? WHERE book_id = ?";
		try (PreparedStatement ps = conn.prepareStatement(sql)) {
			ps.setBoolean(1, available);
			ps.setInt(2, bookId);
			return ps.executeUpdate() == 1;
		}
	}

	private static Book map(ResultSet rs) throws SQLException {
		return new Book(rs.getInt("book_id"), rs.getString("isbn"), rs.getString("title"), rs.getString("author"),
				rs.getObject("published_on", LocalDate.class), rs.getBigDecimal("replacement_cost"),
				rs.getBoolean("available"));
	}
}
