package library;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import library.dao.BookDao;
import library.domain.Book;
import library.errors.AppException;

/**
 * A scratch main: exercises BookDao with no web server.
 *
 * Run it a second time to see the duplicate ISBN. The DAO translates the
 * SQLException (error 1062) into a ConflictException, with the original
 * SQLException kept as its cause.
 */
public class BookDaoDemo {

	public static void main(String[] args) {
		BookDao dao = new BookDao();

		// 1. List every book
		List<Book> books = dao.findAll();
		for (Book b : books) {
			System.out.println(
					b.bookId() + ": " + b.title() + " by " + b.author() + (b.available() ? "" : " (checked out)"));
		}

		// 2. Insert a new book
		Book newBook = new Book(null, "9780441013593", "Dune Messiah", "Frank Herbert", LocalDate.of(1969, 10, 15),
				new BigDecimal("16.00"), true);
		try {
			int id = dao.insert(newBook);
			System.out.println("Inserted book " + id);

			// 3. Look it up again: available comes from the column default
			Optional<Book> found = dao.findById(id);
			if (found.isEmpty()) {
				System.out.println("Book " + id + " was inserted but can't be found");
			} else {
				System.out.println("Found: " + found.get());
			}
		} catch (AppException e) {
			// 5. Second run: the ISBN is already there
			System.out.println("Insert failed: " + e.getClass().getSimpleName() + ": " + e.getMessage());
			if (e.getCause() instanceof SQLException) {
				SQLException cause = (SQLException) e.getCause();
				System.out.println(
						"  caused by SQLState " + cause.getSQLState() + ", vendor code " + cause.getErrorCode());
			}
		}

		// 4. A book that doesn't exist
		System.out.println("Book 9999: " + dao.findById(9999));
	}
}
