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;

/**
 * Test BookDao without a web server.
 *
 * Run it a second time to see the duplicate-ISBN SQLException (error 1062).
 */
public class BookDaoDemo {

    public static void main(String[] args) throws SQLException {
        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 (SQLException e) {
            // 5. Second run: the ISBN is already there
            System.out.println("Insert failed: " + e.getMessage());
            System.out.println("  SQLState " + e.getSQLState() + ", vendor code " + e.getErrorCode());
        }

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