package library.dao;

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

import library.db.DB;
import library.domain.Loan;

/**
 * The SQL for LOANS that checkout and return need.
 *
 * Methods that take a Connection run inside a transaction (Transactions.run):
 * they use the transaction's connection instead of opening their own, and leave
 * SQLException to the transaction. findById(int) stands alone.
 */
public class LoanDao {

	private static final String COLUMNS = "loan_id, book_id, member_id, checked_out_on, due_on, returned_on";

	// Return, before its transaction: does the loan exist, and is it still out?
	public Optional<Loan> findById(int loanId) {
		try (Connection conn = DB.getConnection()) {
			return findById(conn, loanId);
		} catch (SQLException e) {
			throw SqlErrors.translate(e);
		}
	}

	// The same, inside a transaction (re-reading a loan the transaction just wrote)
	public Optional<Loan> findById(Connection conn, int loanId) throws SQLException {
		String sql = "SELECT " + COLUMNS + " FROM LOANS WHERE loan_id = ?";
		try (PreparedStatement ps = conn.prepareStatement(sql)) {
			ps.setInt(1, loanId);
			try (ResultSet rs = ps.executeQuery()) {
				if (rs.next()) {
					return Optional.of(map(rs));
				}
				return Optional.empty();
			}
		}
	}

	// Checkout → returns the new loan_id. returned_on is left out, so it starts as
	// NULL.
	// A member_id with no MEMBERS row fails here with error 1452 (foreign key).
	public int insert(Connection conn, Loan loan) throws SQLException {
		String sql = "INSERT INTO LOANS (book_id, member_id, checked_out_on, due_on) " + "VALUES (?, ?, ?, ?)";
		try (PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
			ps.setInt(1, loan.bookId());
			ps.setInt(2, loan.memberId());
			ps.setObject(3, loan.checkedOutOn());
			ps.setObject(4, loan.dueOn());
			ps.executeUpdate();
			try (ResultSet keys = ps.getGeneratedKeys()) {
				keys.next();
				return keys.getInt(1);
			}
		}
	}

	// Return → false if the loan was already returned. The IS NULL condition makes
	// a second return of the same loan change nothing, even if two arrive at once.
	public boolean markReturned(Connection conn, int loanId, LocalDate returnedOn) throws SQLException {
		String sql = "UPDATE LOANS SET returned_on = ? WHERE loan_id = ? AND returned_on IS NULL";
		try (PreparedStatement ps = conn.prepareStatement(sql)) {
			ps.setObject(1, returnedOn);
			ps.setInt(2, loanId);
			return ps.executeUpdate() == 1;
		}
	}

	private static Loan map(ResultSet rs) throws SQLException {
		return new Loan(rs.getInt("loan_id"), rs.getInt("book_id"), rs.getInt("member_id"),
				rs.getObject("checked_out_on", LocalDate.class), rs.getObject("due_on", LocalDate.class),
				rs.getObject("returned_on", LocalDate.class)); // null while still out
	}
}
